diff --git a/Lib/test/test_genericclass.py b/Lib/test/test_genericclass.py index 37a87bc6815ec2..3088a736ea168f 100644 --- a/Lib/test/test_genericclass.py +++ b/Lib/test/test_genericclass.py @@ -264,6 +264,13 @@ def __class_getitem__(cls, item): return 'from __class_getitem__' self.assertEqual(C[int], 'from metaclass') + def test_class_getitem_in_runtime(self): + class C: + pass + + C.__class_getitem__ = lambda cls, item: f'{cls.__name__}[{item.__name__}]' + + self.assertEqual(C[int], 'C[int]') @support.cpython_only class CAPITest(unittest.TestCase): diff --git a/Misc/ACKS b/Misc/ACKS index c9fa08bd614138..86a9ac9d3505a8 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -1847,3 +1847,4 @@ Doug Zongker Peter Åstrand Zheao Li Carsten Klein +Batuhan Taskaya diff --git a/Objects/typeobject.c b/Objects/typeobject.c index e6cf4fbf30aeb6..7efcf7c26a2e92 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -3264,6 +3264,16 @@ type_setattro(PyTypeObject *type, PyObject *name, PyObject *value) type->tp_name); return -1; } + + if (PyUnicode_Check (name) + && (!strcmp (PyUnicode_AsUTF8 (name), "__init_subclass__") + || !strcmp (PyUnicode_AsUTF8 (name), "__class_getitem__")) + && PyFunction_Check (value)) + { + value = PyClassMethod_New (value); + } + + if (PyUnicode_Check(name)) { if (PyUnicode_CheckExact(name)) { if (PyUnicode_READY(name) == -1)