GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — support narrowing enum values using `==` and `!=` · Issue #10915 · python/mypy

support narrowing enum values using == and != #10915

New issue
Copy link
New issue
Copy link
Closed
#11521
Closed
support narrowing enum values using == and !=#10915
#11521
Copy link
Labels
featuretopic-enumtopic-type-narrowingConditional type narrowing / binder

Description

@DetachHead
DetachHead
opened on Aug 3, 2021
Issue body actions
from typing import NoReturn, Literal
from enum import auto, Enum

def foo(value: Literal["foo","bar"]) -> None:
    if value == "foo":
        reveal_type(value) #note: Revealed type is "Literal['foo']"
    elif value != "bar":
        reveal_type(value) #error: Statement is unreachable  [unreachable]

class Foo(Enum):
    foo = auto()
    bar = auto()

def bar(value: Foo) -> None:
    if value == Foo.foo:
        reveal_type(value) #Revealed type is "__main__.Foo"
    elif value != Foo.bar:
        reveal_type(value) #no error, even though this is unreachable

https://mypy-play.net/?mypy=latest&python=3.10&flags=show-column-numbers%2Cshow-error-codes%2Cstrict%2Ccheck-untyped-defs%2Cdisallow-any-decorated%2Cdisallow-any-expr%2Cdisallow-any-explicit%2Cdisallow-any-generics%2Cdisallow-any-unimported%2Cdisallow-incomplete-defs%2Cdisallow-subclassing-any%2Cdisallow-untyped-calls%2Cdisallow-untyped-decorators%2Cdisallow-untyped-defs%2Cwarn-incomplete-stub%2Cwarn-redundant-casts%2Cwarn-return-any%2Cwarn-unreachable%2Cwarn-unused-configs%2Cwarn-unused-ignores&gist=0f58b3bb7b93c7e3d917c18a7df2ed39

Reacted by KotlinIsland and Felipe S. S. Schneider

Activity

  1. DetachHead
    added
    feature
    on Aug 3, 2021
  2. erictraut commented on Aug 3, 2021

    @erictraut
    erictraut
    on Aug 3, 2021
    More actions

    If you use the is and is not operators rather than == and !=, mypy will perform narrowing for enum values.

  3. KotlinIsland commented on Aug 3, 2021

    @KotlinIsland
    KotlinIsland
    on Aug 3, 2021
    Contributor
    More actions

    Why? is it an anti pattern to use ==/!= on enum values? if so should a warning be raised when they are used?.

  4. erictraut commented on Aug 3, 2021

    @erictraut
    erictraut
    on Aug 3, 2021
    More actions

    I don't know why mypy handles is and is not but not == and != in this case. I'm guessing that the former is more common than the latter. I think both patterns are reasonable. I can't think of a reason why == and != would be an anti-pattern. FWIW, pyright supports type narrowing for both pairs of operators.

    Reacted by KotlinIsland and Felipe S. S. Schneider
  5. DetachHead
    changed the title [-]support narrowing enum values[/-] [+]support narrowing enum values using `==` and `!=`[/+] on Aug 3, 2021
  6. hauntsaninja commented on Aug 3, 2021

    @hauntsaninja
    hauntsaninja
    on Aug 3, 2021
    Collaborator
    More actions

    If you want to give implementing this a shot take a look at #7000, in particular #7000 (comment)

  7. KotlinIsland commented on Nov 11, 2021

    @KotlinIsland
    KotlinIsland
    on Nov 11, 2021
    Contributor
    More actions

    @hauntsaninja Would this be as simple as changing:

    mypy/mypy/checker.py

    Line 4476 in 421fcc2

    coerce_only_in_literal_context = True

    To be False if the comparison is against an Enum?

  8. hauntsaninja commented on Nov 11, 2021

    @hauntsaninja
    hauntsaninja
    on Nov 11, 2021
    Collaborator
    More actions

    Yeah, should be something like that. You'll want to restrict to when the comparison is against an Enum that has a last_known_value. Let me play around and see...

  9. KotlinIsland commented on Nov 11, 2021

    @KotlinIsland
    KotlinIsland
    on Nov 11, 2021
    Contributor
    More actions

    coerce_only_in_literal_context = False if all(isinstance(p := get_proper_type(t), Instance) and p.type.is_enum for t in expr_types) else True
    I wrote this, but it looks pretty cringe.

  10. hauntsaninja commented on Nov 11, 2021

    @hauntsaninja
    hauntsaninja
    on Nov 11, 2021
    Collaborator
    More actions

    This is what I'm playing with:

    diff --git a/mypy/checker.py b/mypy/checker.py
    index 95789831f..d8e65f73c 100644
    --- a/mypy/checker.py
    +++ b/mypy/checker.py
    @@ -4802,7 +4802,16 @@ class TypeChecker(NodeVisitor[None], CheckerPluginInterface):
             """
             should_coerce = True
             if coerce_only_in_literal_context:
    -            should_coerce = any(is_literal_type_like(operand_types[i]) for i in chain_indices)
    +
    +            def should_coerce_inner(typ: Type) -> bool:
    +                typ = get_proper_type(typ)
    +                return is_literal_type_like(typ) or (
    +                    isinstance(typ, Instance)
    +                    and typ.type.is_enum
    +                    and (typ.last_known_value is not None)
    +                )
    +
    +            should_coerce = any(should_coerce_inner(operand_types[i]) for i in chain_indices)
     
             target: Optional[Type] = None
             possible_target_indices = []
    

    We do have test cases that explicitly test against this behaviour though :-( most notably testNarrowingEqualityFlipFlop.

  11. KotlinIsland commented on Nov 11, 2021

    @KotlinIsland
    KotlinIsland
    on Nov 11, 2021
    Contributor
    More actions

    Were they added when enums is comparisons were added.

    To make sure that they wouldn't work on == due to complications.

  12. KotlinIsland commented on Nov 11, 2021

    @KotlinIsland
    KotlinIsland
    on Nov 11, 2021
    Contributor
    More actions

    But now that we are implementing it correctly we should change the tests.

  13. KotlinIsland commented on Nov 11, 2021

    @KotlinIsland
    KotlinIsland
    on Nov 11, 2021
    Contributor
    More actions

    and (typ.last_known_value is not None)
    When would it be an enum and None?

  14. hauntsaninja commented on Nov 11, 2021

    @hauntsaninja
    hauntsaninja
    on Nov 11, 2021
    Collaborator
    More actions

    It'd be the case in

    def f(x: Medal, y: Medal):
        if x == y: ...
    

    Probably fine to omit that check, since coerce_to_literal won't do anything if last_known_value is None (actually that's not true, it'll narrow singleton enums as well, so probably good to omit it, barring some chaining weirdness).

    Yeah, the tests are pretty explicit about why they test what they test:

    mypy/test-data/unit/check-narrowing.test

    Line 720 in d41e34a

    # So strictly speaking, we ought to do the same thing with 'is' comparisons

    I'm not convinced that those tests are necessarily the behaviour we want, but seems like whoever wrote them collected some data / spent more time thinking about this specific issue than I have, so just saying I'd need to think about it too! :-)

  15. KotlinIsland commented on Nov 11, 2021

    @KotlinIsland
    KotlinIsland
    on Nov 11, 2021
    Contributor
    More actions

    That looks like a scenario like:

    def m():
        global a
        a = 2
    
    a: int = True
    
    if a is True:
        m()
        reveal_type(a)  # Literal[True]

    Sus!

  16. KotlinIsland commented on Nov 11, 2021

    @KotlinIsland
    KotlinIsland
    on Nov 11, 2021
    Contributor
    More actions

    What's the policy on narrowing mutable variables? seems to me like that example with narrowing to True is the same as that test?

  17. hauntsaninja commented on Nov 11, 2021

    @hauntsaninja
    hauntsaninja
    on Nov 11, 2021
    Collaborator
    More actions

    Yeah, I'm inclined to agree (although literal types always make things murkier in practice). Although the test case specifically tests enums, it's possible that the real world false positives alluded to were more often narrowing to literal strs or something. I can make the PR and we'll see what other mypy maintainers have to say.

    Reacted by KotlinIsland
  18. hauntsaninja
    added a commit that references this issue on Nov 11, 2021

    Allow narrowing enum values using ==

    This issue will close once commit db11aa5 is merged into the 'master' branch.
    db11aa5
  19. 97littleleaf11
    added
    topic-enum
    on Feb 19, 2022
  20. parsons-kyle-89 commented on Apr 1, 2022

    @parsons-kyle-89
    parsons-kyle-89
    on Apr 1, 2022
    More actions

    Last I checked (which was all the way back in version 0.790), the behavior was even stranger than presented here. == did narrow narrow Enums in if-else blocks, but only if they followed an is. See #9786

    Reacted by DetachHead and KotlinIsland
  21. AlexWaygood
    added
    topic-type-narrowingConditional type narrowing / binder
    on Apr 4, 2022
  22. KotlinIsland commented on Feb 9, 2023

    @KotlinIsland
    KotlinIsland
    on Feb 9, 2023
    Contributor
    More actions

    This makes match on enums really annoying.

  23. hauntsaninja commented on Feb 9, 2023

    @hauntsaninja
    hauntsaninja
    on Feb 9, 2023
    Collaborator
    More actions

    I don't really use match. Could you paste a semi-realistic example where merging #11521 would help?

  24. KotlinIsland commented on Feb 9, 2023

    @KotlinIsland
    KotlinIsland
    on Feb 9, 2023
    Contributor
    More actions

    Good point, I don't know why I used a match...

    But I could imagine if anyone ever does use a match that this will be annoying.

  25. hauntsaninja
    closed this as completedin #11521on Apr 24, 2023
  26. hauntsaninja
    added a commit that references this issue on Apr 24, 2023

    Allow narrowing enum values using == (#11521)

    This issue will close once commit 0061d6e is merged into the 'master' branch.
    0061d6e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featuretopic-enumtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.