Add type hints to _util#7642
Conversation
|
Thinking about this some more, the if sys.version_info >= (3, 10):
from typing import TypeGuard
PathGuard = TypeGuard[bytes | str | Path]
elif typing.TYPE_CHECKING:
from typing_extensions import TypeGuard
PathGuard = TypeGuard[bytes | str | Path]
else:
PathGuard = bool
def is_path(f) -> PathGuard:
return isinstance(f, (bytes, str, Path))However, I'm not sure if this is worth doing to avoid the hard dependency, and if so, how the dependency should be declared in |
|
Other than for testing, we've managed to avoid Python dependencies so far. I doubt adding Another option is to leave if sys.version_info >= (3, 10):
from typing import TypeGuard
PathGuard = TypeGuard[bytes | str | Path]
else:
PathGuard = boolAnd use new Python for type checking; we use 3.12 on the CI. This could also be tidied into an internal module. |
for more information, see https://pre-commit.ci
|
After a lot of trial and error, I've managed to make Even if we later add a hard dependency on |
Co-authored-by: Hugo van Kemenade <[email protected]>
Helps #2625.
I wanted to start adding type hints for
PIL.ImageFont, but it is still in the list of excluded files.The errors in
ImageFontcan be fixed by adding type hints forPIL._utiland an empty_imagingft.pyifile.There are three issues in
ImageFont:Solved by adding empty
_imagingft.pyifile, which reveals another error:Solved by adding
_util.DeferredError.new(ex) -> Any.I think this should be
typing.BinaryIO, Handle pathlib.Path in FreeTypeFont #7578 (comment).Note that typeshed has
_typeshed.SupportsRead[bytes].several more errors due to failed propagation of the
_util.is_pathtype guardSolved by adding type hints for
_util.is_path. This requires the use oftyping.TypeGuardwhich is Python 3.10+ only. For Python<=3.9, it is taken fromtyping_extensions. See https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-new-additions-to-the-typing-module for more information.I've also included fixes for errors in
ImageFile(incorrectImageFile._Tile.argsannotation) andImageCms(missing_imagingcms.pyifile), as they are quite simple.