Home >Backend Development >Python Tutorial >How Do I Implement and Use Enumerations in Python?
Implementing Enumerations in Python
Python provides a built-in enum module in Python 3.4 or above. This module allows for the representation of enumerations, which are collections of named constants. To use it, you can follow these steps:
Import the enum module:
import enum
Define the enumeration:
Animal = enum.Enum('Animal', 'ant bee cat dog')
Access the members of the enumeration:
Animal.ant # returns <Animal.ant: 1> Animal['ant'] # returns <Animal.ant: 1> (string lookup) Animal.ant.name # returns 'ant' (inverse lookup)
Alternatively, you can define an enumeration using a class-based approach:
class Animal(enum.Enum): ant = 1 bee = 2 cat = 3 dog = 4
Earlier Versions of Python
In earlier versions of Python, you can create your own custom enum functionality using a class:
class Enum(object): def __init__(self, *args): self.keys = args def __getattr__(self, attr): try: return attr, self.keys.index(attr) except: raise AttributeError(attr)
Using typing.Literal in MyPy
When using MyPy for type checking, you can also express enumerations using typing.Literal:
from typing import Literal Animal: Literal['ant', 'bee', 'cat', 'dog']
The above is the detailed content of How Do I Implement and Use Enumerations in Python?. For more information, please follow other related articles on the PHP Chinese website!