Replace io.BytesIO in type hints

This commit is contained in:
Hugo van Kemenade 2024-01-22 21:37:37 +02:00
parent 1185fb8296
commit 231d54b9df
6 changed files with 38 additions and 10 deletions

View File

@ -1,5 +1,5 @@
Internal Reference Docs
=======================
Internal Reference
==================
.. toctree::
:maxdepth: 2

View File

@ -33,6 +33,18 @@ Internal Modules
Provides a convenient way to import type hints that are not available
on some Python versions.
.. py:class:: FileDescriptor
Typing alias.
.. py:class:: StrOrBytesPath
Typing alias.
.. py:class:: SupportsRead
An object that supports the read method.
.. py:data:: TypeGuard
:value: typing.TypeGuard

View File

@ -27,11 +27,12 @@
"""
from __future__ import annotations
from io import BytesIO
from typing import IO
from . import ImageFile, ImagePalette, UnidentifiedImageError
from ._binary import i16be as i16
from ._binary import i32be as i32
from ._typing import FileDescriptor, StrOrBytesPath
class GdImageFile(ImageFile.ImageFile):
@ -80,7 +81,9 @@ class GdImageFile(ImageFile.ImageFile):
]
def open(fp: BytesIO, mode: str = "r") -> GdImageFile:
def open(
fp: StrOrBytesPath | FileDescriptor | IO[bytes], mode: str = "r"
) -> GdImageFile:
"""
Load texture from a GD image file.

View File

@ -14,17 +14,16 @@
#
from __future__ import annotations
from io import BytesIO
from . import Image, ImageFile
from ._binary import i8
from ._typing import SupportsRead
#
# Bitstream parser
class BitStream:
def __init__(self, fp: BytesIO) -> None:
def __init__(self, fp: SupportsRead[bytes]) -> None:
self.fp = fp
self.bits = 0
self.bitbuffer = 0

View File

@ -1,6 +1,8 @@
from __future__ import annotations
import os
import sys
from typing import Protocol, TypeVar, Union
if sys.version_info >= (3, 10):
from typing import TypeGuard
@ -15,4 +17,16 @@ else:
return bool
__all__ = ["TypeGuard"]
_T_co = TypeVar("_T_co", covariant=True)
class SupportsRead(Protocol[_T_co]):
def read(self, __length: int = ...) -> _T_co:
...
FileDescriptor = int
StrOrBytesPath = Union[str, bytes, "os.PathLike[str]", "os.PathLike[bytes]"]
__all__ = ["FileDescriptor", "TypeGuard", "StrOrBytesPath", "SupportsRead"]

View File

@ -4,10 +4,10 @@ import os
from pathlib import Path
from typing import Any, NoReturn
from ._typing import TypeGuard
from ._typing import StrOrBytesPath, TypeGuard
def is_path(f: Any) -> TypeGuard[bytes | str | Path]:
def is_path(f: Any) -> TypeGuard[StrOrBytesPath]:
return isinstance(f, (bytes, str, Path))