Description
Feature or enhancement
Allow defining a GenericAlias-like thing that implements custom logic but can still interact with typing.py
as if it was a GenericAlias
.
Pitch
This is useful for things that want to do runtime type checking/tracking, including Pydantic and Numpy, and has zero impact on static type checkers.
Pydantic
class Model(BaseModel, Generic[T]):
x: int
# need to track TypeVar substitution for data validation
# requiring BaseModel.__class_getitem__ to return something
# that is not a GenericAlias
Model[int](x='abc')
# needs to work at runtime, currently crashes w/ typing_extensions and only works on some version of CPython (including current main)
# but could be broken at any moment without a test
List[Model[T]][int]
# ideally these would work both for Pydantic's sake and for any other tools introspecting types
get_args(Model[T][int])
Numpy
I'm attempting to summarize how this applies to the discusion in TypingSig but full disclosure I am not the original author or a Numpy developer.
ST = TypeVar("ST")
DT = np.dtype[ST]
actual = DT[np.float64]
If np.dtype[ST]
returns a "generic alias like" thing then that thing can implement __getitem__
and return a concrete np.Float64Dtype
or whatever when it gets substituted with np.float64
.
Implementation
Most of this already works in typing.py
on CPython main. I only will need to tweak get_args
and get_origin
.
On the other hand, typing_extensions
and older versions of CPython break if you do List[MyGenericClass[T]][int]
because List
doesn't recognize that MyGenericClass
has generic parameters. So half other the feature request here is to add tests for existing behavior so that it is standardized and doesn't change going forward.
Previous discussion
Discussed a PyCon 2023 typing summit, my personal impression was a generally positive reception of the features request.