diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 2ceaff7baeee23..ec44ed6b7124b2 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -3206,6 +3206,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 2f4c5cd7e7d2c3..007078ca3754b2 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);