Python - Enums

Enum, IntEnum

Posted by Rico's Nerd Cluster on January 15, 2019

IntEnum

  • IntEnum’s members are ints, while enum instance’s members are its own class
    • Enum: Base class for creating enumerated constants.
    • IntEnum: Base class for creating enumerated constants that are also subclasses of int.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      
        class Shape(IntEnum):
            CIRCLE = 1
            SQUARE = 2
      
        class Color(Enum):
            RED = 1
            GREEN = 2
      
        Shape.CIRCLE == Color.RED
        >> False
      
        Shape.CIRCLE == 1
        >>True
      
    • Also, this would raise: ValueError: invalid literal for int() with base 10: 'a'
      1
      2
      3
      4
      5
      
        class State(IntEnum):
            READY = 'a'
            IN_PROGRESS = 'b'
            FINISHED = 'c'
            FAILED = 'd'
      
    • Create IntEnum instance with data:
      1
      
        self.motor_error_code = MotorErrorCode(self.motor_error_code)