Search code examples
pythonenums

Python equivalent of C# Enum.HasFlag


Lets say in python

StateA = 1
StateB = 2
StateC = StateA | StateB

...
instance.state = StateA

in C# there is a HasFlag function in Enum, which tells me an object's flag is part of StateC

Is there a equivalent version in python?

Right now I can only think (as bitwise noob) of this and not even sure if it supposed to work:

if instance.state | StateC == StateC:
    # yes in StateC

Solution

  • Testing for a flag:

    value & flag == flag
    

    Adding a flag:

    value |= flag
    

    Clearing a flag:

    value &= ~flag