B12 - enum

source: Indently and python documentation

enum

  • a set of symbolic names bound to unique variables

from enum import Enum

class Color(Enum):
	RED: str = "R"
	GREEN: str = "G"
	BLUE: str = "B"
 
def create_car(color: Color) -> None:
    match color:
        case Color.RED:
            print("Red car")
        case Color.GREEN:
            print("Green car")
        case Color.BLUE:
            print("Blue car")
        case _:
            print("Unknown color")
            
color = input("Enter a color: ").upper()
create_car(Color[color])

flags

from enum import Flag

class Color(Flag):
    ## using powers of 2 to make it easier to combine colors
	RED: int = 1
	GREEN: int = 2
	BLUE: int = 4
	YELLOW: int = 8
	BLACK: int = 16

yellow_and_red = Color.RED | Color.YELLOW
print(yellow_and_red.value) ## prints 9
from enum import Flag, auto   

class Color(Flag):
    ## using powers of 2 to make it easier to combine colors
    RED: int = auto()
    GREEN: int = auto()
    BLUE: int = auto()
    YELLOW: int = auto()
    BLACK: int = auto()
    ALL: int = RED | GREEN | BLUE | YELLOW | BLACK

print(Color.ALL.value) ## 31
print(Color.RED in Color.ALL) ## True

duplication

class Shape(Enum):
	SQUARE = 2
	SQUARE = 3
	
## invalid: TypeError


class Shape(Enum):
	SQUARE = 2
	DIAMOND = 1
	CIRCLE = 3
	SQ = 2

## valid
from enum import Enum, unique

@unique
class State(Enum):
    ONE: int = 1
    TWO: int = 2
    THREE: int = 3
    FOUR: int = 3
    
## invalid: ValueError