enum
Initialization
  • enum.Enum, base class for creating enumerated constants
  • from enum import Enum
    
    class Color(Enum):
        RED = 10
        GREEN = 20
        BLUE = 30
    list(Color) # [, , ]
        
    Animal = Enum('Animal', 'ANT BEE CAT DOG')
    list(Animal) # [, , , ]
                
    Access
    Color.RED == 10 # False
    
    # Color.RED RED 10
    # Color.GREEN GREEN 20
    # Color.BLUE BLUE 30
    for color in Color:
        print(color, color.name, color.value)
    
    Color(10) # <Color.RED: 10>
    Color['RED'] # <Color.RED: 10>
    Color.RED # <Color.RED: 10>
    
    Color(10) == Color.RED # True
    
    Color(10).name # 'RED'
    Color.RED.value # 10
                
    Methods
  • Enum class decorator that ensures only one name is bound to any one value
  • # enum.unique()
    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
    from enum import Enum, auto
    class Color(Enum):
        RED = auto()
        BLUE = auto()
        GREEN = auto()
    
    print(list(Color)) # [, , ]
                
  • A subclass of enum. Assign each item an integer value
  • # enum.IntEnum
    from enum import IntEnum
    
    class Shape(IntEnum):
        CIRCLE = 1
        SQUARE = 2
        
    print(Shape.CIRCLE == 1) # True
                
  • Integer-based enum
  • Members can be combined using the bitwise operators (&, |, ^, ~)
  • # enum.IntFlag
    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
                
  • Members can be combined using the bitwise operators (&, |, ^, ~)
  • cannot be combined with, nor compared against, any other Flag enumeration, nor int
  • # enum.Flag
    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>]
    
    Color.RED & Color.GREEN # <Color.0: 0>
    Color.RED | Color.GREEN # <Color.GREEN|RED: 5>
    Color.RED ^ Color.GREEN # <Color.GREEN|RED: 5>
    ~ Color.RED # <Color.GREEN|BLUE: 6>
                
    Built-in Functions
    list(Color) # [<Color.RED: 10>, <Color.GREEN: 20>, <Color.BLUE: 30>]
                
    Reference
  • Python 3 Standard Library
  • PyMOTW-3