Skip to content

[mypyc] Borrow final attributes more aggressively#21702

Open
JukkaL wants to merge 30 commits into
masterfrom
mypyc-final
Open

[mypyc] Borrow final attributes more aggressively#21702
JukkaL wants to merge 30 commits into
masterfrom
mypyc-final

Conversation

@JukkaL

@JukkaL JukkaL commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

Final attributes can't be rebound after initialization, so we can borrow them more aggressively than regular attributes, as long as the base object is kept alive for the duration of the borrowing. This allows skipping some incref/decref operations, and it adds significantly more opportunities for borrowing on free-threaded builds, in particular, as borrowing non-final attributes is very restricted.

For example, the attribute x can only be safely borrowed if it's Final, since otherwise foo could assign to the attribute and free the old value:

def func(o: C) -> None:
    foo(o.x)

There are some subtleties in the implementation. Here are the main things that required extra care:

  • We don't allow borrowed values to escape from conditionally executed code paths (e.g. conditional expressions, comprehensions).
  • If a local variable can be modified with an assignment expression, we restrict borrowing based on that variable.
  • We can only borrow for a longer duration if the attribute value doesn't depend on a subexpression with a smaller borrow scope.
  • Lambda expressions generate a complete separate expression and borrowing scope.

I used coding agent assist, especially for tests, but created the implementation is short, individually reviewed increments.

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

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.

1 participant