Skip to content

Setting __module__ doesn't remove __firstlineno__ when the class has a custom metaclass #162572

Backlog

Description

@Robertboy18

Bug report

Bug description:

The docs say "Setting the __module__ attribute removes the __firstlineno__ item from the type's dictionary" (type.__firstlineno__). For a class whose metaclass is written in Python (abc.ABC, enum.Enum, class M(type): pass) it stays, so inspect.getsource returns lines of the module named by the new __module__, the problem of gh-123339:

import abc, inspect
class P: pass
class A(abc.ABC): pass
for c in (P, A):
    c.__module__ = "inspect"  # any other imported module
    print(c.__name__, "__firstlineno__" in c.__dict__, end=" ")
    try: print(repr(inspect.getsource(c)[:40]))
    except (OSError, TypeError) as e: print(type(e).__name__, e)
P False OSError source code not available
A True 'This module encapsulates the interface p'

The metaclass's own __module__ string in its __dict__ comes before the __module__ descriptor of type in the lookup, so the assignment just stores into the class's __dict__ and type_set_module (Objects/typeobject.c), which removes __firstlineno__, never runs. I found it while writing a Lean spec of Python.

CPython versions tested on:

3.15, CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    type-bug
    interpreter-core
    on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions