Home >Backend Development >Python Tutorial >How Can I Effectively Represent Enums in Python?
In Python 3.4 and later, enums can be natively defined using the Enum class. To use it, install the enum34 package for Python versions prior to 3.4.
from enum import Enum Animal = Enum('Animal', 'ant bee cat dog') print(Animal.ant) # Output: <Animal.ant: 1> print(Animal['ant']) # Output: <Animal.ant: 1> print(Animal.ant.name) # Output: 'ant'
For more advanced enum techniques, consider using the aenum library.
In earlier Python versions, enums can be emulated using a custom function:
def enum(**enums): return type('Enum', (), enums)
Usage:
Numbers = enum(ONE=1, TWO=2, THREE='three') print(Numbers.ONE) # Output: 1 print(Numbers.THREE) # Output: 'three'
One can also support automatic enumeration with:
def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums)
Usage:
Numbers = enum('ZERO', 'ONE', 'TWO') print(Numbers.ZERO) # Output: 0 print(Numbers.TWO) # Output: 2
Alternatively, use typing.Literal from Python 3.8 or typing_extensions.Literal in earlier versions to define enums:
from typing import Literal # Python >= 3.8 from typing_extensions import Literal # Python 2.7, 3.4-3.7 Animal = Literal['ant', 'bee', 'cat', 'dog'] def hello_animal(animal: Animal): print(f"hello {animal}")
The above is the detailed content of How Can I Effectively Represent Enums in Python?. For more information, please follow other related articles on the PHP Chinese website!