From 6bcf807fe2cb82c859fb757a498edfe5692ededa Mon Sep 17 00:00:00 2001 From: Nulano Date: Wed, 27 Dec 2023 00:17:57 +0100 Subject: [PATCH] add type hints for _util --- pyproject.toml | 3 +++ src/PIL/_util.py | 23 +++++++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 193e8c9b2..0c25edeb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,9 @@ classifiers = [ dynamic = [ "version", ] +dependencies = [ + 'typing-extensions; python_version < "3.10"', +] [project.optional-dependencies] docs = [ "furo", diff --git a/src/PIL/_util.py b/src/PIL/_util.py index 4634d335b..d11cbfa58 100644 --- a/src/PIL/_util.py +++ b/src/PIL/_util.py @@ -1,21 +1,36 @@ from __future__ import annotations import os +import sys from pathlib import Path +from typing import Any, NoReturn + +if sys.version_info >= (3, 10): + from typing import TypeGuard +else: + from typing_extensions import TypeGuard -def is_path(f): +def is_path(f: Any) -> TypeGuard[bytes | str | Path]: return isinstance(f, (bytes, str, Path)) -def is_directory(f): +def is_directory(f: Any) -> TypeGuard[bytes | str | Path]: """Checks if an object is a string, and that it points to a directory.""" return is_path(f) and os.path.isdir(f) class DeferredError: - def __init__(self, ex): + def __init__(self, ex: BaseException): self.ex = ex - def __getattr__(self, elt): + def __getattr__(self, elt: str) -> NoReturn: raise self.ex + + @staticmethod + def new(ex: BaseException) -> Any: + """ + Creates an object that raises the wrapped exception ``ex`` when used, + and casts it to :py:obj:`~typing.Any` type. + """ + return DeferredError(ex)