Skip to content

Commit 49cd68f

Browse files
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
1 parent d914283 commit 49cd68f

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

Lib/test/test_types.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -737,6 +737,16 @@ def __eq__(self, other):
737737
with self.assertRaises(ZeroDivisionError):
738738
list[int] | list[bt]
739739

740+
union_ga = (int | list[str], int | collections.abc.Callable[..., str],
741+
int | d)
742+
# Raise error when isinstance(type, type | genericalias)
743+
for type_ in union_ga:
744+
with self.subTest(f"check isinstance/issubclass is invalid for {type_}"):
745+
with self.assertRaises(TypeError):
746+
isinstance(list, type_)
747+
with self.assertRaises(TypeError):
748+
issubclass(list, type_)
749+
740750
def test_ellipsis_type(self):
741751
self.assertIsInstance(Ellipsis, types.EllipsisType)
742752

Objects/unionobject.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ is_generic_alias_in_args(PyObject *args) {
3434
Py_ssize_t nargs = PyTuple_GET_SIZE(args);
3535
for (Py_ssize_t iarg = 0; iarg < nargs; iarg++) {
3636
PyObject *arg = PyTuple_GET_ITEM(args, iarg);
37-
if (Py_TYPE(arg) == &Py_GenericAliasType) {
37+
if (PyObject_TypeCheck(arg, &Py_GenericAliasType)) {
3838
return 0;
3939
}
4040
}

0 commit comments

Comments
 (0)