B12 - enum
source: Indently and python documentation
enum
- a set of symbolic names bound to unique variables
-
offer
repr(), grouping, type-safety, etc -
most useful when variables can take a limited selection of values
-
repr()of a member shows the enum name, the member name and the value
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
- allows combination of several enums into a single variable
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
-
powers of 2 are used as, say if
BLACK: int = 9,print(yellow_and_redwould printColor.BLACK -
to make it easier,
auto()can be used
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
- for
Flag, powers of 2 are auto assigned, but forEnum, it will just be integers
duplication
- two enum members with the same name is invalid, but a member can have other associated names
class Shape(Enum):
SQUARE = 2
SQUARE = 3
## invalid: TypeError
class Shape(Enum):
SQUARE = 2
DIAMOND = 1
CIRCLE = 3
SQ = 2
## valid
- to disable this behaviour, the
unique()decorator can be used
from enum import Enum, unique
@unique
class State(Enum):
ONE: int = 1
TWO: int = 2
THREE: int = 3
FOUR: int = 3
## invalid: ValueError