Skip to content

enum.Flag.__contains__ changed behavior since python 3.12#131045

@timrid

Description

@timrid

Bug report

Bug description:

I noticed some strange behavior with enum.Flag an the __contains__ method in Python 3.12/3.13, as shown in the following examples.

Problem 1: Behavior changes at runtime
In the following code snippet the first print statement returns False, which is expected, since 3 is not a member of Weekday. However, the second print statement returns True, which is unexpected, since 3 is still not a member of Weekday.

importenumclassWeekday(enum.Flag): MONDAY=1TUESDAY=2WEDNESDAY=4THURSDAY=8FRIDAY=16SATURDAY=32SUNDAY=64print(f"{3inWeekday}") # => False (expected)_=Weekday.MONDAY|Weekday.TUESDAYprint(f"{3inWeekday}") # => True (not expected)

Problem 2: Behavior is not comparable to Python 3.11
Since Python 3.12 the behavior of Enum.__contains__ has changed, so that it is possible to compare not only with an enum-member, but also with non-enum-members (see here or here). So with Python 3.11 the code above will raise an TypeError: unsupported operand type(s) for 'in': 'int' and 'EnumType'. There you have to change the code to the following. But this in turn always produces unexpected behavior in Python 3.12/3.13.

importenumclassWeekday(enum.Flag): MONDAY=1TUESDAY=2WEDNESDAY=4THURSDAY=8FRIDAY=16SATURDAY=32SUNDAY=64print(f"{Weekday(3) inWeekday}") # => Python 3.11: False (expected) Python 3.12/3.13: True (not expected)_=Weekday.MONDAY|Weekday.TUESDAYprint(f"{Weekday(3) inWeekday}") # => Python 3.11: False (expected) Python 3.12/3.13: True (not expected)

Conclusion
I would have expected that in all cases the result is False, but since Python 3.12 it gets very strange...

CPython versions tested on:

3.12, 3.13

Operating systems tested on:

Windows

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.12only security fixes3.13bugs and security fixes3.14bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions