In this post we will have a look on enums in pythons:
- class Game(Enum): - define enum
- Game(1) - access enum
- add new element to enum dynamically
- test if string / int is in the enum values
- for k in Game: - loop over enum
Since python 3.4 and The PEP 435 enums were included in python. So this article covers python 3.4 and above.
Create enum in python
Declare two enumerations types in Python:
- Sport with 5 sports - box tennis karate running chess
- Game with 4 games inside - dota mario tetris chess
Sport = Enum('Sport', 'box tennis karate running chess')
class Game(Enum):
dota = 1
mario = 2
tetris = 3
chess = 4
Accessing enumerate elements
Accessing python enumerate can be done in several ways:
print(Sport.box) # returns Sport.box
print(Sport['box'] ) # returns Sport.box
print(Sport.box.name) # returns box
print(range(len(Game))) # return range(0, 4)
print(Game(1)) # return Game.dota
print(Game(1).name) # dota
result:
Sport.box
Sport.box
box
range(0, 4)
Game.dota
dota
Adding new elements to enum
Accessing python enum can be done in several ways:
Sport = Enum('Sport', 'box tennis karate running chess')
names = [m.name for m in Sport] + ['wrestling', 'fitness']
Sport = Enum('Sport', names)
for k in Sport:
a = getattr(Sport, k.name)
print(a.name, end=", ")
result:
box, tennis, karate, running, chess, wrestling, fitness,
Testing enumerates for values
Accessing python enum can be done in several ways:
Sport = Enum('Sport', 'box tennis karate running chess')
if(Sport.box in Sport):
print('box is ok')
# String
if('boxing' in Sport.__members__):
print('ok')
else:
print('boxing is missing')
# int
games = [item.value for item in Game]
if(4 in games):
print('4 is in the Enum numbers')
result:
box is ok
boxing is missing
4 is in the Enum numbers
Loop over enums in python
Accessing python enumerates can be done in several ways:
#
# simple loop over enums
#
for sport in Sport:
print(sport)
for game in Game:
print(game)
#
#loop by number
#
for k in range(len(Game)):
a = Game(k +1)
print(a)
#
#loop by name
#
for k in Sport:
a = getattr(Sport, k.name)
print(a.name)
result:
Sport.box, Sport.tennis, Sport.karate, Sport.running, Sport.chess,
Game.dota, Game.mario, Game.tetris, Game.chess,
dota, mario, tetris, chess,
box, tennis, karate, running, chess,