I am having some issues working with the typing types in Python for any more than type hinting:
>>> from typing import List >>> string_list = ['nobody', 'expects', 'the', 'spanish', 'inqusition'] >>> string_list_class = List[str] Now I would like to
- Check if
string_listconforms tostring_list_class. - Check if
string_list_classis a list. - If so, check the class, that
string_list_classis a list of.
I find myself unable to achieve any of those:
>>> isinstance(string_list, string_list_class) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 708, in __instancecheck__ return self.__subclasscheck__(type(obj)) File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 716, in __subclasscheck__ raise TypeError("Subscripted generics cannot be used with" TypeError: Subscripted generics cannot be used with class and instance checks >>> issubclass(string_list_class, List) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 716, in __subclasscheck__ raise TypeError("Subscripted generics cannot be used with" TypeError: Subscripted generics cannot be used with class and instance checks The documentation also is not really helpful with that. Also the API does not seem to be intended to be used that way, however, I need to use that functionality.
Bodging around
A way I found to answer 2. is, that
>>> type(string_list_class) <class 'typing._GenericAlias'> Tough I have no access to _GenericAlias I can build it myself:
>>> _GenericAlias = type(List[str]) >>> isinstance(string_list_class, _GenericAlias) True However that does not seem like a good solution at all and it also yields True for other classes like Collection.
For 1. and 3. I could imagine hacking something together with repr(type(string_list)) and repr(string_list_class) and somehow comparing that string to something, but that also is not a good solution.
But there must be a better way to do this
string_listconforms tostring_list_class, then you already know that it's a list. And I have no idea what point 3 is supposed to mean.string_list_classis a List type in general. It might be a list ofstr,int,MyObjector something else. This is unrelated to 1. With 3 I want to extractMyObjectfromList[MyObject].