Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fixed Incorrect type of enum in 'if' clause #20234#20248

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
sherlock2215 wants to merge2 commits intopython:master
base:master
Choose a base branch
Loading
fromsherlock2215:master

Conversation

@sherlock2215
Copy link

Fixes#20234 --- Correct Enum Literal Narrowing forin Operator with Tuples

Problem

When using thein operator with tuples containing enum members, mypy
failed to narrow the left-hand side to the correct enum literal type.

Before this fix:

ifpizzain (Pizza.MARGHERITA,):reveal_type(pizza)# Revealed: Pizza# Expected: Literal[Pizza.MARGHERITA]

Mypy treated the tuple contents as regularInstance types and did not
extract the literal enum values, so narrowing never happened.


Solution

Enhancedcomparison_type_narrowing_helper to detect tuples containing
enum literals and correctly narrow the type based on the enum values
inside the tuple.

Key Points:

  • Enum values inside tuples appear asInstance types, not
    LiteralType.
  • Their literal identity is available vialast_known_value.
  • The fix extracts these literal values, builds aUnion of enum
    literals, and applies narrowing on the true branch of thein
    expression.

Implementation Details

File:mypy/checker.py
Function:comparison_type_narrowing_helper

Added enum-specific logic immediately after the existingNone-removal
narrowing for thein operator:

  • Extract literal enum values from the tuple's items\
  • Construct aUnion[Literal[Enum.X], Literal[Enum.Y], ...]\
  • Use that union as the narrowed type for the LHS\
  • Supports bothin andnot in

Tests & Behavior

Correctly handled:

  • Single enum in tuple
    python if op in (Op.A,): reveal_type(op) # Literal[Op.A]
  • Multiple enums
    python if op in (Op.A, Op.B): reveal_type(op) # Literal[Op.A] | Literal[Op.B]
  • Works withnot in
  • Preserves existing None-removal behavior

Example

fromenumimportEnumclassOp(Enum):A="a"B="b"defprocess(op:Op)->None:ifopin (Op.A,):reveal_type(op)# Literal[Op.A]returnifopisOp.B:reveal_type(op)# Literal[Op.B]return

@github-actions
Copy link
Contributor

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

psycopg (https://github.com/psycopg/psycopg)+ tests/pq/test_pgconn.py:508: error: Non-overlapping equality check (left operand type: "Literal[ConnStatus.STARTED, ConnStatus.MADE]", right operand type: "Literal[ConnStatus.OK]")  [comparison-overlap]prefect (https://github.com/PrefectHQ/prefect)+ src/prefect/flows.py:3103: error: Redundant cast to "str"  [redundant-cast]+ src/prefect/flows.py:3116: error: Redundant cast to "str"  [redundant-cast]core (https://github.com/home-assistant/core)- homeassistant/components/shelly/event.py:305: error: Argument 1 to "_trigger_event" of "EventEntity" has incompatible type "Any | None"; expected "str"  [arg-type]pytest (https://github.com/pytest-dev/pytest)+ src/_pytest/config/argparsing.py:247: error: Statement is unreachable  [unreachable]steam.py (https://github.com/Gobot1234/steam.py)- steam/ext/csgo/state.py:180: error: Argument "slot" to "Sticker" has incompatible type "int | None"; expected "Literal[0, 1, 2, 3, 4, 5] | None"  [arg-type]+ steam/ext/csgo/state.py:180: error: Argument "slot" to "Sticker" has incompatible type "int"; expected "Literal[0, 1, 2, 3, 4, 5] | None"  [arg-type]discord.py (https://github.com/Rapptz/discord.py)+ discord/app_commands/models.py:900: error: Unused "type: ignore" comment  [unused-ignore]+ discord/threads.py:286: error: Unused "type: ignore" comment  [unused-ignore]xarray (https://github.com/pydata/xarray)+ xarray/backends/writers.py:841: error: Unused "type: ignore" comment  [unused-ignore]

ifisinstance(get_proper_type(iterable_type),TupleType):
# Check if this is an enum instance that can be narrowed
tuple_type=get_proper_type(iterable_type)
fori,item_typeinenumerate(tuple_type.items):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Suggested change
fori,item_typeinenumerate(tuple_type.items):
foritem_typeintuple_type.items:

fori,item_typeinenumerate(tuple_type.items):
ifisinstance(item_type,Instance):

ifitem_type.type.is_enum:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

combine with the previous if statement (line 6601)

Comment on lines +6596 to +6597
literal_types= []
ifisinstance(get_proper_type(iterable_type),TupleType):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Suggested change
literal_types= []
ifisinstance(get_proper_type(iterable_type),TupleType):
ifisinstance(get_proper_type(iterable_type),TupleType):
literal_types= []

@A5rocks
Copy link
Collaborator

Please don't use an LLM to generate the description or responses! We're fine with extremely short or curt text (I've made so many PRs where the description was just a "fixes [link]"...), and making it longer just wastes time.

Additionally, could you add test cases to the tests? Mypy has an extensive unit test suite. (I know you mentioned them in the PR description, but really they belong as a test case)

@sherlock2215
Copy link
Author

Thanks for the info, i thought the LLM prompt was so detailed, i'll add a shorter PR next time and fix the tests:)

A5rocks reacted with thumbs up emojiA5rocks reacted with heart emoji

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

1 more reviewer

@grayjkgrayjkgrayjk left review comments

Reviewers whose approvals may not affect merge requirements

Assignees

No one assigned

Labels

pendingIssues that may be closed

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Incorrect type of enum in "if" clause

4 participants

@sherlock2215@A5rocks@grayjk@hauntsaninja

[8]ページ先頭

©2009-2025 Movatter.jp