2

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

3 Answers 3

4

Python 3.4 has an Enum data type, which has been backported.

from enum import Enum

class States(Enum):
    StateA = 1
    StateB = 2
    StateC = StateA | StateB
    def has_flag(self, flag):
        return self.value & flag.value

if States.StateC.has_flag(States.StateA):
    print("yup, it's there!")

Python 3.6 has the (Int)Flag data type, which is also present in the aenum1 library:

from enum import Flag  # or from aenum import Flag

class States(Flag):
    StateA = 1
    StateB = 2
    StateC = StateA | StateB

if States.StateA in States.StateC:
    print("yup, it's there!")

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Sign up to request clarification or add additional context in comments.

Comments

3

Testing for a flag:

value & flag == flag

Adding a flag:

value |= flag

Clearing a flag:

value &= ~flag

Comments

1

HasFlag is basically bitwise operation.

>>> a = 0b01
>>> b = 0b10
>>> "{0:b}".format(a | b,)
'11'
>>> def has_flag(v, flag): return v & flag == flag
...
>>> has_flag(0b111, a)
True
>>> has_flag(0b111, a|b)
True
>>> has_flag(0b1, a|b)
False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.