James Lin
James Lin

Reputation: 26538

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

Upvotes: 2

Views: 1556

Answers (3)

Ethan Furman
Ethan Furman

Reputation: 69041

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.

Upvotes: 4

Dyno Fu
Dyno Fu

Reputation: 9044

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

Upvotes: 1

user2085282
user2085282

Reputation: 1107

Testing for a flag:

value & flag == flag

Adding a flag:

value |= flag

Clearing a flag:

value &= ~flag

Upvotes: 3

Related Questions