4. Enum

4.1. Why?

  • List of finite choices
  • Enumerations

4.2. Definition

Code Listing 4.11. Defining enum
from enum import Enum


class Color(Enum):
    RED = '#00FF00'
    GREEN = '#00FF00'
    BLUE = '#0000FF'


my_color = Color.RED

4.3. Usage

Code Listing 4.12. Using enum
from enum import Enum


class Color(Enum):
    RED = '#00FF00'
    GREEN = '#00FF00'
    BLUE = '#0000FF'


print(Color.RED)        # Color.RED
print(Color.RED.name)   # RED
print(Color.RED.value)  # '#00FF00'


for color in Color:
    print(color)

# Color.RED
# Color.GREEN
# Color.BLUE


my_color = Color('#00FF00')     # <Color.GREEN: '#00FF00'>
my_color is Color.RED           # False
my_color is Color.GREEN         # True

4.4. Case Study

Code Listing 4.13. enum - Example usage
from enum import Enum


class Permission(Enum):
    READ_WRITE_EXECUTE = 0b111
    READ_WRITE = 0b110
    READ_EXECUTE = 0b101
    READ = 0b100
    WRITE_EXECUTE = 0b011
    WRITE = 0b010
    EXECUTE = 0b001
    NONE = 0b000
Code Listing 4.14. enum - Example usage
from enum import IntEnum


class IndexDrives(IntEnum):
    """ This enum holds the index value of drive object entrys
    """
    ControlWord = 0x6040
    StatusWord = 0x6041
    OperationMode = 0x6060
Code Listing 4.15. enum - Example usage
from enum import Enum


class Color(Enum):
    RED = 'Roscosmos'
    BLUE = 'NASA'


class Moon:
    def __init__(self, explorer):
        self.color = Color(explorer)


moon = Moon(explorer='NASA')


if moon.color is Color.BLUE:
    print("That's one small step for [a] man, one giant leap for mankind.")

elif moon.color is Color.RED:
    print('Красная Луна, товарищ!')

4.5. Assignments