From 18e33cb742ce637a25dfac224683273f88d05363 Mon Sep 17 00:00:00 2001 From: Fidget-Spinner <28750310+Fidget-Spinner@users.noreply.github.com> Date: Sat, 2 Jan 2021 18:05:32 +0800 Subject: [PATCH] raise typeerror when passing subclasses of genericaliases into isinstance/issubclass --- Lib/test/test_types.py | 10 ++++++++++ Objects/unionobject.c | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py index 83196ad3c17436..d8a48ce36f618c 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 32aa5078afcef4..05350363eed63f 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; } }