Home > Backend Development > Python Tutorial > How Can I Effectively Represent Enums in Python?

How Can I Effectively Represent Enums in Python?

DDD
Release: 2024-12-13 09:30:14
Original
377 people have browsed it

How Can I Effectively Represent Enums in Python?

Representing 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'
Copy after login

For more advanced enum techniques, consider using the aenum library.

Alternative Approaches for Pre-Python 3.4

In earlier Python versions, enums can be emulated using a custom function:

def enum(**enums):
    return type('Enum', (), enums)
Copy after login

Usage:

Numbers = enum(ONE=1, TWO=2, THREE='three')
print(Numbers.ONE)  # Output: 1
print(Numbers.THREE)  # Output: 'three'
Copy after login

One can also support automatic enumeration with:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)
Copy after login

Usage:

Numbers = enum('ZERO', 'ONE', 'TWO')
print(Numbers.ZERO)  # Output: 0
print(Numbers.TWO)  # Output: 2
Copy after login

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}")
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template