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

false narrowing on Enum == when Enum has custom __eq__ #2373

Closed
KotlinIsland opened this issue Oct 5, 2021 · 4 comments
Closed

false narrowing on Enum == when Enum has custom __eq__ #2373

KotlinIsland opened this issue Oct 5, 2021 · 4 comments
Labels
as designed Not a bug, working as intended

Comments

@KotlinIsland
Copy link

KotlinIsland commented Oct 5, 2021

from enum import Enum, auto
from typing import Literal


class MyEnum(Enum):
    A = auto()
    B = auto()

    def __eq__(self, other: object) -> bool:
        return True

def func(m: MyEnum) -> None:
    if m == MyEnum.A:
        a: Literal[MyEnum.A] = m  # m could be MyEnum.B here

Maybe don't narrow if the Enum has a custom __eq__ defined or inherited?

@DetachHead
Copy link

related: python/mypy#10915

@erictraut
Copy link
Collaborator

Static type checkers need to make certain assumptions, and a language as dynamic as Python will always provide ways to violate those assumptions. I think this falls into the category of "don't do this if you want static type checking to work".

@erictraut erictraut added the as designed Not a bug, working as intended label Oct 5, 2021
@KotlinIsland
Copy link
Author

I believe in typecheckers being as strict as possible, I would always prefer false positives over false negatives.

But you do you.

@erictraut
Copy link
Collaborator

erictraut commented Oct 5, 2021

It's not so simple in this case. This involves a heuristic ("narrowing is unsafe with there's a customer __eq__ method") that will produce correct results some of the time and incorrect results other times. When the heuristic turns out to be wrong and type narrowing isn't applied, false positives will likely be the result. Rather than add more complexity that's going to eliminate some false positives and create others, I'd rather avoid the complexity and additional layers of special casing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
as designed Not a bug, working as intended
Projects
None yet
Development

No branches or pull requests

3 participants