enum

enum.Enum

  • Base class for creating enumerated constants
In [39]:
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    
print(Color.RED == 1) # False
    
for color in Color:
    print(color)

print(Color(1)) # Color.RED
print(Color['RED']) # Color.RED

print(Color(1).name) # RED
print(Color.RED.value) # 1

# odict_items([('RED', <Color.RED: 1>), ('GREEN', <Color.GREEN: 2>), ('BLUE', <Color.BLUE: 3>)])
print(Color.__members__.items()) 

print(Color(1) == Color.RED) # True
#print(Color(2) > Color(1)) # TypeError, cannot implement greater-than and less-than comparison

#Color(1).value = 10 #AttributeError, cannot set attribute

# define Animal
Animal = Enum('Animal', 'ANT BEE CAT DOG')
print(list(Animal)) #[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]
False
Color.RED
Color.GREEN
Color.BLUE
Color.RED
Color.RED
RED
1
odict_items([('RED', <Color.RED: 1>), ('GREEN', <Color.GREEN: 2>), ('BLUE', <Color.BLUE: 3>)])
True
[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]

enum.unique()

  • Enum class decorator that ensures only one name is bound to any one value
In [ ]:
from enum import Enum, unique

# enum allows different names have same value
class Mistake(Enum):
    ONE = 1
    TWO = 2
    THREE = 3
    FOUR = 3
    
# decorator unique guarrantee all values are unique
# if more than one names have same value, throw ValueError
@unique
class Mistake2(Enum):
    ONE = 1
    TWO = 2
    THREE = 3
    FOUR = 3

enum.auto

In [ ]:
from enum import Enum, auto
class Color(Enum):
    RED = auto()
    BLUE = auto()
    GREEN = auto()

print(list(Color)) # [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

enum.IntEnum

  • a subclass of enum and int
In [38]:
from enum import IntEnum

class Shape(IntEnum):
    CIRCLE = 1
    SQUARE = 2
    
print(Shape.CIRCLE == 1) # True
Shape.CIRCLE

enum.IntFlag

  • is also based on int
  • members can be combined using the bitwise operators (&, |, ^, ~)
In [50]:
from enum import IntFlag

class Perm(IntFlag):
    R = 4
    W = 2
    X = 1
    
a = Perm.R | Perm.W # Perm.R|W
print(a.value) # 6
b = Perm.R + Perm.W 
print(b) # 6
6
6

enum.Flag

  • members can be combined using the bitwise operators (&, |, ^, ~)
  • cannot be combined with, nor compared against, any other Flag enumeration, nor int
In [57]:
from enum import Flag, auto

class Color(Flag):
    RED = auto()
    BLUE = auto()
    GREEN = auto()
    
print(list(Color)) # [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 4>]

b = Color.RED & Color.GREEN # Color.0
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 4>]