Skip to content

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

Closed
@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.

import enum

class Weekday(enum.Flag):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 4
    THURSDAY = 8
    FRIDAY = 16
    SATURDAY = 32
    SUNDAY = 64

print(f"{3 in Weekday}") # => False (expected)
_ = Weekday.MONDAY | Weekday.TUESDAY
print(f"{3 in Weekday}") # => 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.

import enum

class Weekday(enum.Flag):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 4
    THURSDAY = 8
    FRIDAY = 16
    SATURDAY = 32
    SUNDAY = 64

print(f"{Weekday(3) in Weekday}") # => Python 3.11: False (expected)    Python 3.12/3.13: True (not expected)
_ = Weekday.MONDAY | Weekday.TUESDAY
print(f"{Weekday(3) in Weekday}") # => 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 fixesstdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions