[Python-checkins] bpo-42195: Disallow isinstance/issubclass for subclasses of genericaliases in Union (GH-24059)

miss-islington webhook-mailer at python.org
Sat Jan 2 11:19:19 EST 2021


https://github.com/python/cpython/commit/49cd68fb1ed4cbaf109308c0a7c8c1efcf6f3775
commit: 49cd68fb1ed4cbaf109308c0a7c8c1efcf6f3775
branch: master
author: Ken Jin <28750310+Fidget-Spinner at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2021-01-02T08:19:15-08:00
summary:

bpo-42195: Disallow isinstance/issubclass for subclasses of genericaliases in Union (GH-24059)



Previously this didn't raise an error. Now it will:
```python
from collections.abc import Callable
isinstance(int, list | Callable[..., str])
```
Also added tests in Union since there were previously none for stuff like ``isinstance(list, list | list[int])`` either.

Backport to 3.9 not required.

Automerge-Triggered-By: GH:gvanrossum

files:
M Lib/test/test_types.py
M Objects/unionobject.c

diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
index 83196ad3c1743..d8a48ce36f618 100644
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -737,6 +737,16 @@ def __eq__(self, other):
         with self.assertRaises(ZeroDivisionError):
             list[int] | list[bt]
 
+        union_ga = (int | list[str], int | collections.abc.Callable[..., str],
+                    int | d)
+        # Raise error when isinstance(type, type | genericalias)
+        for type_ in union_ga:
+            with self.subTest(f"check isinstance/issubclass is invalid for {type_}"):
+                with self.assertRaises(TypeError):
+                    isinstance(list, type_)
+                with self.assertRaises(TypeError):
+                    issubclass(list, type_)
+
     def test_ellipsis_type(self):
         self.assertIsInstance(Ellipsis, types.EllipsisType)
 
diff --git a/Objects/unionobject.c b/Objects/unionobject.c
index 32aa5078afcef..05350363eed63 100644
--- a/Objects/unionobject.c
+++ b/Objects/unionobject.c
@@ -34,7 +34,7 @@ is_generic_alias_in_args(PyObject *args) {
     Py_ssize_t nargs = PyTuple_GET_SIZE(args);
     for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
         PyObject *arg = PyTuple_GET_ITEM(args, iarg);
-        if (Py_TYPE(arg) == &Py_GenericAliasType) {
+        if (PyObject_TypeCheck(arg, &Py_GenericAliasType)) {
             return 0;
         }
     }



More information about the Python-checkins mailing list