]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42195: Disallow isinstance/issubclass for subclasses of genericaliases in Union...
authorKen Jin <28750310+Fidget-Spinner@users.noreply.github.com>
Sat, 2 Jan 2021 16:19:15 +0000 (00:19 +0800)
committerGitHub <noreply@github.com>
Sat, 2 Jan 2021 16:19:15 +0000 (08:19 -0800)
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
Lib/test/test_types.py
Objects/unionobject.c

index 83196ad3c17436bc9d83eeb3144cb9d9f7fee87f..d8a48ce36f618cf64c7ed4d9c8cd0a6364ee4d4a 100644 (file)
@@ -737,6 +737,16 @@ class TypesTests(unittest.TestCase):
         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)
 
index 32aa5078afcef41dff1f336facf851ee6785ed6f..05350363eed63f0cfdd33a543a77d85625be294e 100644 (file)
@@ -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;
         }
     }