Skip to content

Comments

Fix loop convergence with redefinitions#20865

Merged
ilevkivskyi merged 4 commits intopython:masterfrom
ilevkivskyi:fix-redefine-convergence
Feb 23, 2026
Merged

Fix loop convergence with redefinitions#20865
ilevkivskyi merged 4 commits intopython:masterfrom
ilevkivskyi:fix-redefine-convergence

Conversation

@ilevkivskyi
Copy link
Member

Currently, we reset the variable type each time we visit the initial definition (textually first assignment). This can cause problems with --allow-redefinition-new:

  • Not all branches will be explored (see added test). This is a correctness problem.
  • Many loops will become runaway (will never converge to a fixed point) while they actually can converge. Currently this is stopped by manual cut-off. This is a performance problem.

The only non-trivial part here is handling of this pattern:

for key in ("key_a", "key_b"):
    some_typed_dict[key]

It is special-cased in regular mode, and this special-casing used to work accidentally with redefinition allowed. Now I simply make the same special-casing apply (since for loops can never be runaway on index).

@github-actions

This comment has been minimized.

@ilevkivskyi
Copy link
Member Author

Repro for meson difference:

[case testNewRedefineAnyOrEmptyUnpackInLoop]
# flags: --allow-redefinition-new --local-partial-types
from typing import Any

def foo() -> None:
    while int():
        data: Any
        x, y = data or ([], [])
        reveal_type(x)
[builtins fixtures/isinstancelist.pyi]

Currently we silently infer Any | list[Never], with this PR we give the error and infer Any | list[Any]. TBH I am not sure this is a regression. Also there is a chance this will be fixed by #20851 Actually, I will probably just merge that one, and try re-basing this PR.

@github-actions

This comment has been minimized.

@github-actions
Copy link
Contributor

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

@ilevkivskyi ilevkivskyi merged commit 270a01d into python:master Feb 23, 2026
24 checks passed
@ilevkivskyi ilevkivskyi deleted the fix-redefine-convergence branch February 23, 2026 19:35
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.

2 participants