Home >Backend Development >Python Tutorial >How Can C# Developers Represent Enums in Python?

How Can C# Developers Represent Enums in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 07:15:17146browse

How Can C# Developers Represent Enums in Python?

Representing Enums in Python

Question:

As a C# developer working on a Python project, how can you represent the equivalent of an Enum in Python?

Answer:

Enumerations (Enums) have been introduced in Python 3.4 as part of PEP 435. They have also been backported to previous versions via third-party libraries like enum34 and aenum.

Using the enum Module (Python 3.4 ):

from enum import Enum

Animal = Enum('Animal', 'ant bee cat dog')

This creates an Animal Enum with members ant, bee, cat, and dog.

Using enum34 Library (Python 2.7 ):

from enum34 import Enum

Animal = Enum('Animal', 'ant bee cat dog')

Using aenum Library (Python 2.7 , 3.3 ):

from aenum import Enum

class Animal(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4

Earlier Technique for Python Pre-3.4:

In earlier versions of Python, you can use a custom enum() function to create your own enums:

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

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

Additional Techniques:

  • Automatic enumeration: Use functions like enum(*sequential, **named) to automatically generate members based on provided names.
  • Reverse mapping: Add a reverse_mapping attribute to your Enum to easily convert values back to names.
  • MyPy typing.Literal: Use typing.Literal to define type-safe enums in Python 3.8 .

The above is the detailed content of How Can C# Developers 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
Previous article:Frame a LogicNext article:Frame a Logic