1

Any exist built in method or best practices to check containers type with typing library? I would like see:

from typing import List
isinstance([1,2,3], List[int])

General problem is different behavior with same syntax:

In [22]: isinstance([1,2], List)
Out[22]: True

In [23]: isinstance([1,2], List[int])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-8598eb948ef8> in <module>()
----> 1 isinstance([1,2], List[int])

/usr/lib/python3.7/typing.py in __instancecheck__(self, obj)
    706 
    707     def __instancecheck__(self, obj):
--> 708         return self.__subclasscheck__(type(obj))
    709 
    710     def __subclasscheck__(self, cls):

/usr/lib/python3.7/typing.py in __subclasscheck__(self, cls)
    714             if cls._special:
    715                 return issubclass(cls.__origin__, self.__origin__)
--> 716         raise TypeError("Subscripted generics cannot be used with"
    717                         " class and instance checks")
    718 

TypeError: Subscripted generics cannot be used with class and instance check```
RuS
  • 71
  • 7
  • 1
    That's not how type hinting works, and your sample code throws a `TypeError`. That's for a reason; the syntax is used for *static type checking*, not dynamic type checking. – Martijn Pieters Oct 03 '18 at 12:43
  • @MartijnPieters Read the question before pls. I wrote code which I want and ask how I can same result – RuS Oct 03 '18 at 12:49
  • I know what you wrote, and you can't have that. That's not what the syntax can do for you. The duplicate explains why. – Martijn Pieters Oct 03 '18 at 12:50
  • If you need to do dynamic type checks, write your own code. Don't use `typing` for this. `isinstance(value, list) and all(isinstance(v, int) for v in value)` would do here, provided you *have* to have this check (the vast majority of software doesn't) and `value` isn't a huge list. – Martijn Pieters Oct 03 '18 at 12:51
  • @MartijnPieters Thx for checking generator example! It's really simplest way to solve it, but general problem is different behavior with same syntax. I modified question, pls check. – RuS Oct 03 '18 at 13:06
  • 1
    From the documenation: *At runtime, `isinstance(x, T)` will raise `TypeError`. In general, `isinstance()` and `issubclass()` should not be used with types.* That an unadorned `List` works with `isinstance()` should not be taken as support for `isinstance()` in general. – Martijn Pieters Oct 03 '18 at 13:48

0 Answers0