From eedf5bd6d17da791effe9d1b6ef882dc474884f2 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Sun, 16 May 2021 11:19:28 -0700 Subject: [PATCH] improve inspect.pyi - Use TypeGuard for various is* functions (refer to #5406) - Use collections.abc and builtin containers --- stdlib/inspect.pyi | 135 ++++++++++++++++++++++----------------------- 1 file changed, 66 insertions(+), 69 deletions(-) diff --git a/stdlib/inspect.pyi b/stdlib/inspect.pyi index fa49e4493b28..850a2782a280 100644 --- a/stdlib/inspect.pyi +++ b/stdlib/inspect.pyi @@ -1,24 +1,21 @@ import enum import sys from collections import OrderedDict -from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import ( - AbstractSet, - Any, - Callable, - ClassVar, - Dict, - Generator, - List, - Mapping, - NamedTuple, - Optional, - Sequence, - Tuple, - Type, - Union, +from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence, Set +from types import ( + AsyncGeneratorType, + BuiltinFunctionType, + CodeType, + CoroutineType, + FrameType, + FunctionType, + GeneratorType, + MethodType, + ModuleType, + TracebackType, ) -from typing_extensions import Literal +from typing import Any, ClassVar, NamedTuple, Optional, Type, Union +from typing_extensions import Literal, TypeGuard # # Types and members @@ -33,7 +30,7 @@ class BlockFinder: indecorator: bool decoratorhasargs: bool last: int - def tokeneater(self, type: int, token: str, srowcol: Tuple[int, int], erowcol: Tuple[int, int], line: str) -> None: ... + def tokeneater(self, type: int, token: str, srowcol: tuple[int, int], erowcol: tuple[int, int], line: str) -> None: ... CO_OPTIMIZED: int CO_NEWLOCALS: int @@ -47,12 +44,12 @@ CO_ITERABLE_COROUTINE: int CO_ASYNC_GENERATOR: int TPFLAGS_IS_ABSTRACT: int -def getmembers(object: object, predicate: Optional[Callable[[Any], bool]] = ...) -> List[Tuple[str, Any]]: ... +def getmembers(object: object, predicate: Optional[Callable[[Any], bool]] = ...) -> list[tuple[str, Any]]: ... def getmodulename(path: str) -> Optional[str]: ... -def ismodule(object: object) -> bool: ... -def isclass(object: object) -> bool: ... -def ismethod(object: object) -> bool: ... -def isfunction(object: object) -> bool: ... +def ismodule(object: object) -> TypeGuard[ModuleType]: ... +def isclass(object: object) -> TypeGuard[Type[Any]]: ... +def ismethod(object: object) -> TypeGuard[MethodType]: ... +def isfunction(object: object) -> TypeGuard[FunctionType]: ... if sys.version_info >= (3, 8): def isgeneratorfunction(obj: object) -> bool: ... @@ -62,9 +59,9 @@ else: def isgeneratorfunction(object: object) -> bool: ... def iscoroutinefunction(object: object) -> bool: ... -def isgenerator(object: object) -> bool: ... -def iscoroutine(object: object) -> bool: ... -def isawaitable(object: object) -> bool: ... +def isgenerator(object: object) -> TypeGuard[GeneratorType]: ... +def iscoroutine(object: object) -> TypeGuard[CoroutineType]: ... +def isawaitable(object: object) -> TypeGuard[Awaitable[Any]]: ... if sys.version_info >= (3, 8): def isasyncgenfunction(obj: object) -> bool: ... @@ -72,11 +69,11 @@ if sys.version_info >= (3, 8): else: def isasyncgenfunction(object: object) -> bool: ... -def isasyncgen(object: object) -> bool: ... -def istraceback(object: object) -> bool: ... -def isframe(object: object) -> bool: ... -def iscode(object: object) -> bool: ... -def isbuiltin(object: object) -> bool: ... +def isasyncgen(object: object) -> TypeGuard[AsyncGeneratorType]: ... +def istraceback(object: object) -> TypeGuard[TracebackType]: ... +def isframe(object: object) -> TypeGuard[FrameType]: ... +def iscode(object: object) -> TypeGuard[CodeType]: ... +def isbuiltin(object: object) -> TypeGuard[BuiltinFunctionType]: ... def isroutine(object: object) -> bool: ... def isabstract(object: object) -> bool: ... def ismethoddescriptor(object: object) -> bool: ... @@ -89,7 +86,7 @@ def ismemberdescriptor(object: object) -> bool: ... # _SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] -def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: Optional[str] = ...) -> str: ... def getblock(lines: Sequence[str]) -> Sequence[str]: ... def getdoc(object: object) -> Optional[str]: ... @@ -97,7 +94,7 @@ def getcomments(object: object) -> Optional[str]: ... def getfile(object: _SourceObjectType) -> str: ... def getmodule(object: object, _filename: Optional[str] = ...) -> Optional[ModuleType]: ... def getsourcefile(object: _SourceObjectType) -> Optional[str]: ... -def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: ... def getsource(object: _SourceObjectType) -> str: ... def cleandoc(doc: str) -> str: ... def indentsize(line: str) -> int: ... @@ -152,7 +149,7 @@ if sys.version_info >= (3, 10): globals: Optional[Mapping[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ..., eval_str: bool = ..., - ) -> Dict[str, Any]: ... + ) -> dict[str, Any]: ... # The name is the same as the enum's name in CPython class _ParameterKind(enum.IntEnum): @@ -184,8 +181,8 @@ class Parameter: class BoundArguments: arguments: OrderedDict[str, Any] - args: Tuple[Any, ...] - kwargs: Dict[str, Any] + args: tuple[Any, ...] + kwargs: dict[str, Any] signature: Signature def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ... def apply_defaults(self) -> None: ... @@ -194,20 +191,20 @@ class BoundArguments: # Classes and functions # -# TODO: The actual return type should be List[_ClassTreeItem] but mypy doesn't +# TODO: The actual return type should be list[_ClassTreeItem] but mypy doesn't # seem to be supporting this at the moment: -# _ClassTreeItem = Union[List[_ClassTreeItem], Tuple[type, Tuple[type, ...]]] -def getclasstree(classes: List[type], unique: bool = ...) -> List[Any]: ... -def walktree(classes: List[type], children: Dict[Type[Any], List[type]], parent: Optional[Type[Any]]) -> List[Any]: ... +# _ClassTreeItem = Union[list[_ClassTreeItem], tuple[type, tuple[type, ...]]] +def getclasstree(classes: list[type], unique: bool = ...) -> list[Any]: ... +def walktree(classes: list[type], children: dict[Type[Any], list[type]], parent: Optional[Type[Any]]) -> list[Any]: ... class ArgSpec(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] keywords: Optional[str] - defaults: Tuple[Any, ...] + defaults: tuple[Any, ...] class Arguments(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] varkw: Optional[str] @@ -215,33 +212,33 @@ def getargs(co: CodeType) -> Arguments: ... def getargspec(func: object) -> ArgSpec: ... class FullArgSpec(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] varkw: Optional[str] - defaults: Optional[Tuple[Any, ...]] - kwonlyargs: List[str] - kwonlydefaults: Optional[Dict[str, Any]] - annotations: Dict[str, Any] + defaults: Optional[tuple[Any, ...]] + kwonlyargs: list[str] + kwonlydefaults: Optional[dict[str, Any]] + annotations: dict[str, Any] def getfullargspec(func: object) -> FullArgSpec: ... class ArgInfo(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] keywords: Optional[str] - locals: Dict[str, Any] + locals: dict[str, Any] def getargvalues(frame: FrameType) -> ArgInfo: ... def formatannotation(annotation: object, base_module: Optional[str] = ...) -> str: ... def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... def formatargspec( - args: List[str], + args: list[str], varargs: Optional[str] = ..., varkw: Optional[str] = ..., - defaults: Optional[Tuple[Any, ...]] = ..., + defaults: Optional[tuple[Any, ...]] = ..., kwonlyargs: Optional[Sequence[str]] = ..., - kwonlydefaults: Optional[Dict[str, Any]] = ..., - annotations: Dict[str, Any] = ..., + kwonlydefaults: Optional[dict[str, Any]] = ..., + annotations: dict[str, Any] = ..., formatarg: Callable[[str], str] = ..., formatvarargs: Callable[[str], str] = ..., formatvarkw: Callable[[str], str] = ..., @@ -250,23 +247,23 @@ def formatargspec( formatannotation: Callable[[Any], str] = ..., ) -> str: ... def formatargvalues( - args: List[str], + args: list[str], varargs: Optional[str], varkw: Optional[str], - locals: Optional[Dict[str, Any]], + locals: Optional[dict[str, Any]], formatarg: Optional[Callable[[str], str]] = ..., formatvarargs: Optional[Callable[[str], str]] = ..., formatvarkw: Optional[Callable[[str], str]] = ..., formatvalue: Optional[Callable[[Any], str]] = ..., ) -> str: ... -def getmro(cls: type) -> Tuple[type, ...]: ... -def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> Dict[str, Any]: ... +def getmro(cls: type) -> tuple[type, ...]: ... +def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> dict[str, Any]: ... class ClosureVars(NamedTuple): nonlocals: Mapping[str, Any] globals: Mapping[str, Any] builtins: Mapping[str, Any] - unbound: AbstractSet[str] + unbound: Set[str] def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... def unwrap(func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = ...) -> Any: ... @@ -279,7 +276,7 @@ class Traceback(NamedTuple): filename: str lineno: int function: str - code_context: Optional[List[str]] + code_context: Optional[list[str]] index: Optional[int] # type: ignore class FrameInfo(NamedTuple): @@ -287,16 +284,16 @@ class FrameInfo(NamedTuple): filename: str lineno: int function: str - code_context: Optional[List[str]] + code_context: Optional[list[str]] index: Optional[int] # type: ignore def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... -def getouterframes(frame: Any, context: int = ...) -> List[FrameInfo]: ... -def getinnerframes(tb: TracebackType, context: int = ...) -> List[FrameInfo]: ... +def getouterframes(frame: Any, context: int = ...) -> list[FrameInfo]: ... +def getinnerframes(tb: TracebackType, context: int = ...) -> list[FrameInfo]: ... def getlineno(frame: FrameType) -> int: ... def currentframe() -> Optional[FrameType]: ... -def stack(context: int = ...) -> List[FrameInfo]: ... -def trace(context: int = ...) -> List[FrameInfo]: ... +def stack(context: int = ...) -> list[FrameInfo]: ... +def trace(context: int = ...) -> list[FrameInfo]: ... # # Fetching attributes statically @@ -324,12 +321,12 @@ CORO_SUSPENDED: str CORO_CLOSED: str # TODO can we be more specific than "object"? def getcoroutinestate(coroutine: object) -> str: ... -def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> Dict[str, Any]: ... +def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> dict[str, Any]: ... # TODO can we be more specific than "object"? -def getcoroutinelocals(coroutine: object) -> Dict[str, Any]: ... +def getcoroutinelocals(coroutine: object) -> dict[str, Any]: ... -# Create private type alias to avoid conflict with symbol of same +# Create private type alias to avoid confdict with symbol of same # name created in Attribute class. _Object = object @@ -339,7 +336,7 @@ class Attribute(NamedTuple): defining_class: type object: _Object -def classify_class_attrs(cls: type) -> List[Attribute]: ... +def classify_class_attrs(cls: type) -> list[Attribute]: ... if sys.version_info >= (3, 9): class ClassFoundException(Exception): ...