Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1.12, 1.13] Regression in enum narrowing #18029

Open
Fred-si opened this issue Oct 24, 2024 · 2 comments
Open

[1.12, 1.13] Regression in enum narrowing #18029

Fred-si opened this issue Oct 24, 2024 · 2 comments
Labels
bug mypy got something wrong topic-enum topic-literal-types topic-type-narrowing Conditional type narrowing / binder topic-union-types

Comments

@Fred-si
Copy link

Fred-si commented Oct 24, 2024

Bug Report

Regression in 1.12.

Try to narrowing union between StrEnum (or IntEnum) and Literal no longer works since mypy 1.12.0

To Reproduce
Issue can be reproduce with this code sample

from typing_extensions import Literal
from typing import Union
from enum import StrEnum

class Foo(StrEnum):
    FOO = 'a'


def foo(a: Union[Foo, Literal['foo']]) -> Foo:
    if a == 'foo':
        return Foo.FOO

    return a

playground link
failing test can be found here

Expected Behavior
After the if branch return, variable type should be narrowed to Foo and mypy should not produce error

Actual Behavior
After the if branch return, variable type is considered as "Union[Foo, Literal['foo']]" and my

Your Environment

  • Mypy version used: 1.12, 1.13, master
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: all versions from 3.8 to 3.13
@Fred-si Fred-si added the bug mypy got something wrong label Oct 24, 2024
@JukkaL
Copy link
Collaborator

JukkaL commented Oct 24, 2024

This bisects to #17866. I'll look into this.

@JukkaL
Copy link
Collaborator

JukkaL commented Oct 25, 2024

Narrowing has the issue already in 1.11, but the recent changes made the issue more prominent. This doesn't work as expected when using mypy 1.11:

from typing_extensions import Literal
from typing import Union

class C:
    def __eq__(self, other): return True

def f(x: Union[C, Literal['foo']]) -> None:
    if x == "foo":
        reveal_type(x)  # Union[__main__.C, Literal['foo']]
    else:
        reveal_type(x)  # Union[__main__.C, Literal['foo']], but expected just C

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-enum topic-literal-types topic-type-narrowing Conditional type narrowing / binder topic-union-types
Projects
None yet
Development

No branches or pull requests

2 participants