Skip to content

Commit 337ff66

Browse files
committed
gh-162572: Remove __firstlineno__ when __module__ is set through a metaclass attribute
1 parent c37d06e commit 337ff66

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

‎Lib/test/test_builtin.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3183,6 +3183,19 @@ def test_type_firstlineno(self):
31833183
A.__firstlineno__ = 43
31843184
self.assertEqual(A.__dict__['__firstlineno__'], 43)
31853185

3186+
def test_type_firstlineno_metaclass_module(self):
3187+
# gh-162572: the metaclass's own __module__ is found before
3188+
# type.__module__ when setting the attribute.
3189+
class M(type):
3190+
pass
3191+
A = M('A', (), {'__firstlineno__': 42})
3192+
self.assertEqual(A.__dict__['__firstlineno__'], 42)
3193+
A.__module__ = 'testmodule'
3194+
self.assertEqual(A.__module__, 'testmodule')
3195+
self.assertNotIn('__firstlineno__', A.__dict__)
3196+
A.__firstlineno__ = 43
3197+
self.assertEqual(A.__dict__['__firstlineno__'], 43)
3198+
31863199
def test_type_typeparams(self):
31873200
class A[T]:
31883201
pass
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Setting the :attr:`~type.__module__` attribute of a class now removes the
2+
:attr:`~type.__firstlineno__` item from the class dictionary also when the
3+
metaclass has a ``__module__`` attribute, for example a metaclass defined in
4+
Python.

‎Objects/typeobject.c‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6850,6 +6850,14 @@ type_setattro(PyObject *self, PyObject *name, PyObject *value)
68506850
Py_DECREF(refs.types[i]);
68516851
}
68526852
#endif
6853+
if (res == 0 && _PyUnicode_Equal(name, &_Py_ID(__module__))) {
6854+
// A __module__ attribute of the metaclass hides type_set_module(),
6855+
// so remove __firstlineno__ here as well.
6856+
PyType_Modified(type);
6857+
if (PyDict_Pop(dict, &_Py_ID(__firstlineno__), NULL) < 0) {
6858+
res = -1;
6859+
}
6860+
}
68536861

68546862
done:
68556863
Py_DECREF(name);

0 commit comments

Comments
 (0)