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

How Can I Effectively Use and Represent Enums in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 00:23:10814browse

How Can I Effectively Use and Represent Enums in Python?

Python Enum Representation

Python provides a native Enum type in version 3.4 and above. For earlier versions, you can use third-party libraries like enum34 or aenum.

Using enum34 or stdlib Enum:

from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')

Animal.ant  # <Animal.ant: 1>
Animal['ant']  # <Animal.ant: 1> (string lookup)
Animal.ant.name  # 'ant' (inverse lookup)

Using aenum:

from aenum import Enum
Animal = Enum('Animal', 'ant bee cat dog')

Animal.ant  # same as enum34
Animal['ant']  # same as enum34
Animal.ant.name  # same as enum34

Using Earlier Python Versions:

For earlier Python versions, you can use a custom function like this:

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

Numbers = enum(ONE=1, TWO=2, THREE='three')
Numbers.ONE  # 1
Numbers.TWO  # 2
Numbers.THREE  # 'three'

Automatic Enumeration:

You can also use the following function for automatic enumeration:

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

Numbers = enum('ZERO', 'ONE', 'TWO')
Numbers.ZERO  # 0
Numbers.ONE  # 1

Reverse Mapping:

To support converting enum values back to names:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse_mapping'] = reverse
    return type('Enum', (), enums)

Numbers = enum('ZERO', 'ONE', 'TWO')
Numbers.reverse_mapping['1']  # 'ONE'

Typing.Literal (MyPy):

In MyPy, you can define enums using Literal:

from typing import Literal

Animal = Literal['ant', 'bee', 'cat', 'dog']

def hello_animal(animal: Animal):
    print(f"hello {animal}")

This will prevent assignments of non-enum values.

The above is the detailed content of How Can I Effectively Use and Represent Enums in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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