Sunday 12 September 2021

Python: Define Enum using functional api

Enum class in python is callable, and you can define enum via functional way like below.

 

Example

Color = Enum('Color', 'RED GREEN BLUE')

 

enumFunctionApi1.py

from enum import Enum

Color = Enum('Color', 'RED GREEN BLUE')

print(list(Color))
print(Color['RED'].name, ' -> ', Color['RED'].value)
print(Color['GREEN'].name, ' -> ', Color['GREEN'].value)
print(Color['BLUE'].name, ' -> ', Color['BLUE'].value)

 

Output

[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
RED  ->  1
GREEN  ->  2
BLUE  ->  3

 

Color = Enum('Color', 'RED GREEN BLUE')

First argument to the enum is the name of enumeration.

Second argument is the source of enumeration member names.

 

Second argument can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values.

 

Example

Color = Enum('Color', [("RED", 20), ("GREEN", 21), ("BLUE", 45)])

 

Find the below working application.

 

enumFunctionApi2.py

from enum import Enum

Color = Enum('Color', [("RED", 20), ("GREEN", 21), ("BLUE", 45)])

print(list(Color))
print(Color['RED'].name, ' -> ', Color['RED'].value)
print(Color['GREEN'].name, ' -> ', Color['GREEN'].value)
print(Color['BLUE'].name, ' -> ', Color['BLUE'].value)

 

Output

[<Color.RED: 20>, <Color.GREEN: 21>, <Color.BLUE: 45>]
RED  ->  20
GREEN  ->  21
BLUE  ->  45

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment