Typing Inspect
The typing_inspect
module defines experimental API for runtime inspection of types defined in the Python standard typing
module. Works with typing
version 3.7.4
and later. Example usage:
from typing import Generic, TypeVar, Iterable, Mapping, Union
from typing_inspect import is_generic_type
T = TypeVar('T')
class MyCollection(Generic[T]):
content: T
assert is_generic_type(Mapping)
assert is_generic_type(Iterable[int])
assert is_generic_type(MyCollection[T])
assert not is_generic_type(int)
assert not is_generic_type(Union[int, T])
Note: The API is still experimental, if you have ideas/suggestions please open an issue on tracker. Currently typing_inspect
only supports latest version of typing
. This limitation may be lifted if such requests will appear frequently.
Currently provided functions (see functions docstrings for examples of usage):
is_generic_type(tp)
: Test iftp
is a generic type. This includesGeneric
itself, but excludes special typing constructs such asUnion
,Tuple
,Callable
,ClassVar
.is_callable_type(tp)
: Testtp
is a generic callable type, including subclasses excluding non-generic types and callables.is_tuple_type(tp)
: Test iftp
is a generic tuple type, including subclasses excluding non-generic classes.is_union_type(tp)
: Test iftp
is a union type.is_optional_type(tp)
: Test iftp
is an optional type (eithertype(None)
or a direct union to it such as inOptional[int]
). Nesting andTypeVar
s are not unfolded/inspected in this process.is_literal_type(tp)
: Test iftp
is a literal type.is_final_type(tp)
: Test iftp
is a final type.is_typevar(tp)
: Test iftp
represents a type variable.is_new_type(tp)
: Test iftp
represents a distinct type.is_classvar(tp)
: Test iftp
represents a class variable.get_origin(tp)
: Get the unsubscripted version oftp
. Supports generic types,Union
,Callable
, andTuple
. ReturnsNone
for unsupported types.get_last_origin(tp)
: Get the last base of (multiply) subscripted typetp
. Supports generic types,Union
,Callable
, andTuple
. ReturnsNone
for unsupported types.get_parameters(tp)
: Return type parameters of a parameterizable typetp
as a tuple in lexicographic order. Parameterizable types are generic types, unions, tuple types and callable types.get_args(tp, evaluate=False)
: Get type arguments oftp
with all substitutions performed. For unions, basic simplifications used byUnion
constructor are performed. Ifevaluate
isFalse
(default), report result as nested tuple, this matches the internal representation of types. Ifevaluate
isTrue
, then all type parameters are applied (this could be time and memory expensive).get_last_args(tp)
: Get last arguments of (multiply) subscripted typetp
. Parameters forCallable
are flattened.get_generic_type(obj)
: Get the generic type ofobj
if possible, or its runtime class otherwise.get_generic_bases(tp)
: Get generic base types oftp
or empty tuple if not possible.typed_dict_keys(td)
: GetTypedDict
keys and their types, or None iftd
is not a typed dict.