From 337ff66384e3553c5247e073f659d9295f2882d5 Mon Sep 17 00:00:00 2001 From: Chetan Sahney Date: Tue, 1 Dec 2026 03:36:42 +0530 Subject: [PATCH 1/2] gh-162572: Remove __firstlineno__ when __module__ is set through a metaclass attribute --- Lib/test/test_builtin.py | 13 +++++++++++++ .../2026-12-01-12-00-00.gh-issue-162572.qPyDkw.rst | 4 ++++ Objects/typeobject.c | 8 ++++++++ 3 files changed, 25 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-12-01-12-00-00.gh-issue-162572.qPyDkw.rst diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index d21de4adc2a98d..b1c798ee164500 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -3183,6 +3183,19 @@ def test_type_firstlineno(self): A.__firstlineno__ = 43 self.assertEqual(A.__dict__['__firstlineno__'], 43) + def test_type_firstlineno_metaclass_module(self): + # gh-162572: the metaclass's own __module__ is found before + # type.__module__ when setting the attribute. + class M(type): + pass + A = M('A', (), {'__firstlineno__': 42}) + self.assertEqual(A.__dict__['__firstlineno__'], 42) + A.__module__ = 'testmodule' + self.assertEqual(A.__module__, 'testmodule') + self.assertNotIn('__firstlineno__', A.__dict__) + A.__firstlineno__ = 43 + self.assertEqual(A.__dict__['__firstlineno__'], 43) + def test_type_typeparams(self): class A[T]: pass diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-12-01-12-00-00.gh-issue-162572.qPyDkw.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-12-01-12-00-00.gh-issue-162572.qPyDkw.rst new file mode 100644 index 00000000000000..00c7fa0af428e6 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-12-01-12-00-00.gh-issue-162572.qPyDkw.rst @@ -0,0 +1,4 @@ +Setting the :attr:`~type.__module__` attribute of a class now removes the +:attr:`~type.__firstlineno__` item from the class dictionary also when the +metaclass has a ``__module__`` attribute, for example a metaclass defined in +Python. diff --git a/Objects/typeobject.c b/Objects/typeobject.c index e16e12b06731a6..ac10ea7305bd3d 100644 --- a/Objects/typeobject.c +++ b/Objects/typeobject.c @@ -6850,6 +6850,14 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value) Py_DECREF(refs.types[i]); } #endif + if (res == 0 && _PyUnicode_Equal(name, &_Py_ID(__module__))) { + // A __module__ attribute of the metaclass hides type_set_module(), + // so remove __firstlineno__ here as well. + PyType_Modified(type); + if (PyDict_Pop(dict, &_Py_ID(__firstlineno__), NULL) < 0) { + res = -1; + } + } done: Py_DECREF(name); From 003c58697ded5bb5c8bdd8c376ed8eeea2c0659c Mon Sep 17 00:00:00 2001 From: Chetan Sahney Date: Wed, 2 Dec 2026 03:33:49 +0530 Subject: [PATCH 2/2] Re-run CLA check