Typing Inspect

0.9.0 · active · verified Sat Mar 28

typing-inspect is a Python library providing runtime inspection utilities for types defined in the standard `typing` module. It is currently at version 0.9.0, is actively maintained, and compatible with Python 3.6 and later. It offers an easy-to-use API for advanced introspection of type hints.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic usage of `typing-inspect` to check for generic types, retrieve type arguments and origins, and identify optional types. It covers `is_generic_type`, `get_args`, `get_origin`, and `is_optional_type`.

from typing import List, Union, Optional, TypeVar
from typing_inspect import is_generic_type, get_args, get_origin, is_optional_type

T = TypeVar('T')

class MyGeneric(List[T]):
    pass

# Example 1: Check if a type is generic
assert is_generic_type(MyGeneric[int]) # This should be True
assert not is_generic_type(int) # This should be False

# Example 2: Get arguments of a type
args = get_args(List[str])
assert args == (str,)

union_type = Union[int, str]
union_args = get_args(union_type)
assert set(union_args) == {int, str}

# Example 3: Get the origin of a type
origin = get_origin(List[int])
assert origin is list

# Example 4: Check for optional types
assert is_optional_type(Optional[int])
assert not is_optional_type(int)

print("All quickstart assertions passed!")

view raw JSON →