def get_Generic_itemtype(sq, simplify=True):
"""Retrieves the item type from a PEP 484 generic or subclass of such.
sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container.
Consequently this also works with typing.List, typing.Set and typing.Dict.
Note that for typing.Dict and mapping types in general, the key type is regarded as item type.
For typing.Tuple all contained types are returned as a typing.Union.
If simplify == True some effort is taken to eliminate redundancies in such a union.
"""
if isinstance(sq, TupleMeta):
if simplify:
itm_tps = [x for x in get_Tuple_params(sq)]
simplify_for_Union(itm_tps)
return Union[tuple(itm_tps)]
else:
return Union[get_Tuple_params(sq)]
else:
try:
res = _select_Generic_superclass_parameters(sq, typing.Container)
except TypeError:
res = None
if res is None:
try:
res = _select_Generic_superclass_parameters(sq, typing.Iterable)
except TypeError:
pass
if res is None:
raise TypeError("Has no itemtype: "+type_str(sq))
else:
return res[0]
评论列表
文章目录