fix(maths): defer Matrix type annotations so import does not NameError - #15265
Conversation
Importing maths.matrix_exponentiation raised 'NameError: name Matrix is not defined' because __mul__ and modular_exponentiation annotate with Matrix before the class name is bound (annotations evaluate eagerly at class-body execution time). Add 'from __future__ import annotations' to defer annotation evaluation, matching the pattern used elsewhere in the repo. Verified on current master: import succeeds (NameError gone) and all 10 doctests pass. Signed-off-by: sudo-ai-git <sudo-ai-git@users.noreply.github.com>
priya-sundaram-dev
left a comment
There was a problem hiding this comment.
Thanks for the clean re-do — this is exactly the minimal fix I hoped for. Verified against the head commit:
- Before (
master):import matrix_exponentiation→NameError: name 'Matrix' is not defined - After: import succeeds,
fibonacci_with_matrix_exponentiation(13, 0, 1) == 144 python -m doctest maths/matrix_exponentiation.py→ 10 passed, 0 failed- ruff / ty green
A single from __future__ import annotations is the right call here — it defers the eager evaluation of the Matrix self-references and matches the pattern already used elsewhere in the repo, with no behavior change. LGTM. 🎉 (build_docs was still pending when I looked; once it's green this is good to go from my side.)
|
@sudo-ai-git @priya-sundaram-dev Which Python versions is this change needed on?!? Our pytests already pass without this change on Python 3.14t (see the file: .python-version) and on Python 3.15t. |
|
Good question — I dug into the version boundary: Needed on CPython ≤ 3.13; a no-op on 3.14+. The module has forward references to the class from inside its own body:
On ≤3.13 function annotations are evaluated eagerly at On 3.14+ PEP 649 makes annotations lazily computed, so they are never evaluated at import unless something touches So this is not needed for our CI (we pin 3.14t/3.15t via .python-version), but it keeps the module importable for anyone on 3.9–3.13, and it matches the |
Describe your change
Checklist
Why
Importing
maths/matrix_exponentiation.pycurrently raises at import time onmaster:__mul__andmodular_exponentiationannotate withMatrixbefore the name is bound in the class body, and annotations evaluate eagerly.What
Two-line fix: add
from __future__ import annotationsto defer annotation evaluation — the same pattern already used across the repo. No behavior change.This supersedes #15103 (closed; the branch was rebased so that PR could not be reopened).
Verification (on current
master)import matrix_exponentiation->NameError: name 'Matrix' is not definedfibonacci_with_matrix_exponentiation(13, 0, 1) == 144python -m doctest maths/matrix_exponentiation.py-> 10 passed, 0 failedruff check maths/matrix_exponentiation.py-> All checks passed!Rebased onto current
masterper @priya-sundaram-dev's request on #15103.