Differences between mypy in isinstance and issubclass from python 3.5 to 3.6 in parameterized generics

Before switching to python 3.6 from python 3.5, this worked:

import typing issubclass(list, typing.List[int]) # returns True isinstance([1, 2 ,3], typing.List[int]) # returns True 

now in python 3.6 both of them raise the following exception:

 TypeError: Parameterized generics cannot be used with class or instance checks 

Is this a new alleged behavior or bug? If it is intended, how can I perform the checks performed by the above code in python 3.6?

+6
source share
2 answers

This is intentional, you should not mix classes with types defined in typing , at least not because the essence of this is from what I understood. A large discussion of this issue is contained in issue #136 Kill __subclasscheck__ , which also introduced this change. The commit message also refers to how isinstance / subclass will raise TypeError s:

Using isinstance() or issubclass() raises a TypeError for almost everything. There are exceptions: [...]

You can compare without specifying the contained types for common types, for example:

 isinstance(list, typing.List[int]) 

but this is the best you can do afaik.

+4
source

If you want to have better type safety in python, your options are somewhat limited. The technique I used is to list a subclass or dict without overriding any properties, methods, etc.

 class ListInts(list): pass new_obj = ListInts() new_obj += [1, 2, 3, 4, 5, 6] print(isinstance(new_obj, ListInts) 
0
source

Source: https://habr.com/ru/post/1263788/


All Articles