Reputation: 7664
With the typing module, it's possible to specify arbitrary nested types, like List[str]
or Dict[str, Dict[str, float]]
. Is there a way to determine whether the type of an object matches such a type? Something along the lines of
>>> from typing import List
>>> isinstance(['a', 'b'], List[str])
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/home/cbieganek/anaconda3/lib/python3.6/typing.py", line 1162, in __instancecheck__
# return issubclass(instance.__class__, self)
# File "/home/cbieganek/anaconda3/lib/python3.6/typing.py", line 1148, in __subclasscheck__
# raise TypeError("Parameterized generics cannot be used with class "
# TypeError: Parameterized generics cannot be used with class or instance checks
I didn't really expect isinstance()
to work for this, but I'm wondering if there is some other accepted way of doing this.
Upvotes: 0
Views: 283
Reputation: 304
Generics appeared in python as a part of type hinting. So convenient way to use List[str] is a type hint for variable or function parameter:
my_list: List[str] = ['1', '2']
or
def do_something(strings: List[str])->None:
...
Most modern IDEs like PyCharm or Athom has plugins which are support static type check for python code, also look at mypy. If strict run time type check is necessary, it's possible to iterate over list and check each item type, but it is not a good design.
Upvotes: 2