Sunday 12 September 2021

Python: IntFlag enum

IntFlag is another variant of enum, where you can perform bitwise operations (&, |, ^, ~) on IntFlag enum members.

 

Example

two_or_four = IntBits.TWO | IntBits.FOUR
one_or_two_or_four_eight = IntBits.ONE | IntBits.TWO | IntBits.FOUR | IntBits.EIGHT

 

IntFlagDemo1.py

from enum import IntFlag

class IntBits(IntFlag):
    ONE = 1
    TWO = 2
    FOUR = 4
    EIGHT = 8

two_or_four = IntBits.TWO | IntBits.FOUR
one_or_two_or_four_eight = IntBits.ONE | IntBits.TWO | IntBits.FOUR | IntBits.EIGHT

print(two_or_four, ' -> ', two_or_four.value)
print(one_or_two_or_four_eight, ' -> ', one_or_two_or_four_eight.value)

print("IntBits.TWO == 2", " -> ", IntBits.TWO == 2)

 

Output

IntBits.TWO == 2  ->  True
IntBits.FOUR|TWO  ->  6
IntBits.EIGHT|FOUR|TWO|ONE  ->  15

 

Since IntFlag members are also subclasses of int they can be combined with them.

 

IntFlagDemo2.py

from enum import IntFlag

class IntBits(IntFlag):
    ONE = 1
    TWO = 2
    FOUR = 4
    EIGHT = 8

print("IntBits.TWO == 2", " -> ", IntBits.TWO == 2)
print("IntBits.TWO | 4", " -> ", (IntBits.TWO | 4).value)

 

Output

IntBits.TWO == 2  ->  True
IntBits.TWO | 4  ->  6

Can I combine one IntFlag type member to other?

Yes, you can do.

 

IntFlagDemo3.py

from enum import IntFlag

class IntBits1(IntFlag):
    ONE = 1
    TWO = 2

class IntBits2(IntFlag):
    FOUR = 4
    EIGHT = 8

print("IntBits1.TWO | IntBits2.FOUR", " -> ", (IntBits1.TWO | IntBits2.FOUR))


Output

IntBits1.TWO | IntBits2.FOUR  ->  IntBits1.IntBits2.FOUR|TWO





 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment