Create custom types using typing module?
Chirag Dhyani
chiragdhyani at gmail.com
Fri May 29 03:39:01 EDT 2020
I am trying to create a custom type on Python 3.7 typing module. The new
type (say Struct) should be same as type tuple. In Python3.6, I was able to
do the same by taking cue from Typing.GenericMeta and typing.TupleMeta.
With typing module updated in Python3.7, GenericMeta and TupleMeta do not
exist, and the special class that I would like to subclass is not possible.
e.g. _VariadicGenericAlias cannot be subclassed.
What I really want is something similar to:
Struct = _VariadicGenericAlias(tuple, (), , inst=False, special=True)
and
assert _origin(Struct[int, str]) == <class 'Struct'>
Note:
def _origin(typ: Any) -> Any:
"""Get the original (the bare) typing class.
Get the unsubscripted version of a type. Supports generic types, Union,
Callable, and Tuple. Returns None for unsupported types. Examples::
get_origin(int) == None
get_origin(ClassVar[int]) == None
get_origin(Generic) == Generic
get_origin(Generic[T]) == Generic
get_origin(Union[T, int]) == Union
get_origin(List[Tuple[T, T]][int]) == list
"""
if isinstance(typ, _GenericAlias):
return typ.__origin__ if typ.__origin__ is not ClassVar else None
if typ is Generic:
return Generic
return None
Deeply appreciate your help around this !!
Thanks,
Chirag
More information about the Python-list
mailing list