[issue44606] Discrepancy between isinstance() and issubclass() for union types

Ken Jin report at bugs.python.org
Tue Jul 13 05:29:29 EDT 2021


Ken Jin <kenjin4096 at gmail.com> added the comment:

@Serhiy
> 2. Different handling of virtual subclasses:

This looks like a bug. I think the union form of isinstance/issubclass should have the same behavior as the tuple form. We promise checking of virtual classes in the docs for union types:
https://docs.python.org/3.10/library/functions.html#issubclass

The fix seems to be changing one line of code in Objects/unionobject.c from PyType_IsSubtype to PyObject_IsSubclass. Since it isn't a large change and it's a bug, I think we can backport it to 3.10 too.

@Serhiy and Guido,
> 1. Different handling of None:

> Ken Jin, should we treat type(None) as a subclass of int|None?

I think we can avoid this special case altogether by converting all None to type(None) when creating _Py_Union. This is what the typing.Union counterpart does, and it is also what PEP 484 says about None https://www.python.org/dev/peps/pep-0484/#using-none:

>>> Union[None, str].__args__
(<class 'NoneType'>, <class 'str'>)

Though I know some people are opinionated about None -> type(None).

This would require adding one more check at https://github.com/python/cpython/blob/3.10/Objects/unionobject.c#L266 .
Maybe this?

if(Py_IsNone(i_element))
    i_element = &_PyNone_Type

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44606>
_______________________________________


More information about the Python-bugs-list mailing list