Skip to content

[mypyc] Call __setattr__ for assignments that come before its definition - #22158

Open
rheard wants to merge 1 commit into
python:masterfrom
rheard:fix-setattr-skip
Open

rheard wants to merge 1 commit into
python:masterfrom
rheard:fix-setattr-skip

Conversation

@rheard

@rheard rheard commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Fixes mypyc/mypyc#1239

In a native class that defines __setattr__, an assignment to one of the class's attributes is compiled to a call to __setattr__. Whether the class has one was checked with ClassIR.get_method(), which only finds methods whose bodies have already been compiled. Assignments in code above the definition wrote the attribute directly instead:

class C:
    def __init__(self) -> None:
        self.x = 0  # __setattr__ wasn't called

    def __setattr__(self, name: str, value: object) -> None:
        print("setattr", name)
        super().__setattr__(name, value)

The same happened in functions and in methods of other classes above the class in the module, and in modules compiled before the one with the class.

Now the check uses the method declarations, which are complete before any function body is compiled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Attribute assignments that come before the definition of __setattr__ don't call it

1 participant