Skip to content

Fix Any identity narrowing of enum sentinels#21674

Open
dannyward630 wants to merge 1 commit into
python:masterfrom
dannyward630:codex/fix-any-sentinel-narrowing
Open

Fix Any identity narrowing of enum sentinels#21674
dannyward630 wants to merge 1 commit into
python:masterfrom
dannyward630:codex/fix-any-sentinel-narrowing

Conversation

@dannyward630

Copy link
Copy Markdown

Fixes #21667.

This prevents identity/equality narrowing from using an Any comparison target to widen a non-Any expression. In the reported sentinel pattern, x: Any still narrows to the enum literal when x is SENTINEL, but the explicitly typed SENTINEL: SentinelType no longer becomes Any in the true branch.

Tests:

  • python runtests.py EnumSentinelComparedToAny
  • python runtests.py check-enum.test
  • python -m mypy --config-file mypy_self_check.ini mypy/checker.py

Disclosure: I used an LLM-assisted coding tool to help inspect the narrowing path and prepare this patch; I reviewed the change and tests before submitting.

@github-actions

github-actions Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

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

spark (https://github.com/apache/spark)
- python/pyspark/sql/pandas/types.py:791: error: Unused "type: ignore" comment  [unused-ignore]
- python/pyspark/sql/pandas/types.py:792: error: Unused "type: ignore" comment  [unused-ignore]

steam.py (https://github.com/Gobot1234/steam.py)
+ steam/ext/commands/commands.py:245: error: Value of type "def [T] Greedy(cls, *args: Any, **kwargs: Any) -> Never" is not indexable  [index]

strawberry (https://github.com/strawberry-graphql/strawberry)
+ strawberry/utils/typing.py:304: error: Incompatible return value type (got "<typing special form>", expected "type")  [return-value]

pydantic (https://github.com/pydantic/pydantic)
+ pydantic/main.py:1300: error: Invalid self argument "BaseModel" to attribute function "__repr_recursion__" with type "Callable[[Representation, Any], str]"  [misc]

cloud-init (https://github.com/canonical/cloud-init)
+ tests/unittests/sources/azure/test_kvp.py:101: error: Item "None" of "HyperVKvpReportingHandler | None" has no attribute "vm_id"  [union-attr]
+ tests/unittests/sources/azure/test_kvp.py:127: error: Item "None" of "HyperVKvpReportingHandler | None" has no attribute "vm_id"  [union-attr]

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.

Type narrowing of Any with is can widen type of variable for enum member to Any

1 participant