I'm storing type information in a variable x:
x = typing.List[str]
Later, this x is passed together with x_value and I want to switch logic depending on whether x is of typing.List. I'm aware that typing shouldn't be used together with isinstance and issubclass hence I am saying is of. Is there any standard, future proof (and Python 3.6 proof) way of doing this issubtype?
import sys
from typing import List
def issubtype(sub_type, parent_type):
if sys.version_info >= (3, 7):
if not hasattr(sub_type, '__origin__') or not hasattr(parent_type, '__origin__'):
return False
if sub_type.__origin__ != parent_type.__origin__:
return False
if isinstance(parent_type.__args__[0], type):
return sub_type.__args__ == parent_type.__args__
return True
else:
if not hasattr(sub_type, '__extra__') or not hasattr(parent_type, '__extra__'):
return False
if sub_type.__extra__ != parent_type.__extra__:
return False
if not parent_type.__args__ or parent_type.__args__ == sub_type.__args__:
return True
return False
assert issubtype(List[str], List[str])
assert issubtype(List[str], List)
assert issubtype(List[int], List[int])
assert not issubtype(List[int], List[str])
When trying to implement this I realise that any good solution would have to recursively check args (which my attempt doesn't do, but for me just knowing if a thing is a list is enough).