Skip to content

Fix narrowing after always-true blocks with allow-redefinition - #22276

Closed
zhengguangzhuo wants to merge 1 commit into
python:masterfrom
zhengguangzhuo:zhengguangzhuo/mypy-allow-redefinition-narrowing-22259
Closed

zhengguangzhuo wants to merge 1 commit into
python:masterfrom
zhengguangzhuo:zhengguangzhuo/mypy-allow-redefinition-narrowing-22259

Conversation

@zhengguangzhuo

Copy link
Copy Markdown

Fixes #22259.

When --allow-redefinition is enabled, narrowing performed inside a statically always-true if True or if TYPE_CHECKING block is lost after the block. The merge logic treated semantically equivalent types as identical and kept the less-narrowed representation, while the unreachable else path could still contribute the pre-if state.

This change preserves the narrowed representation in the new semantics and excludes the unreachable path from the merge. Regression tests cover if True with and without --allow-redefinition, and TYPE_CHECKING with the option enabled.

Verification:

  • Focused tests for check-redefine2, check-unreachable-code, and check-isinstance: 387 passed, 1 skipped, 1 xfailed.
  • Mypy self-check: 347 source files passed.
  • Repository pre-commit hooks on changed files: all applicable hooks passed.
  • git diff --check: passed.

This contribution was prepared with assistance from OpenAI Codex.

@github-actions

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

pwndbg (https://github.com/pwndbg/pwndbg)
- pwndbg/commands/__init__.py:935: error: Unused "type: ignore" comment  [unused-ignore]
- pwndbg/commands/__init__.py: note: In function "OnlyWhenRunning":
- pwndbg/commands/__init__.py:935: error: Item "function" of "Callable[P, T] | None" has no attribute "_pwndbg_only_when_running_allow_core"  [union-attr]
- pwndbg/commands/__init__.py:935: note: Error code "union-attr" not covered by "type: ignore[attr-defined]" comment

scipy-stubs (https://github.com/scipy/scipy-stubs)
- tests/misc/test_submodules_empty.pyi:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports

@A5rocks A5rocks closed this Oct 22, 2026
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.

--allow-redefinition discards narrowing done in if TYPE_CHECKING/if True block

2 participants