How can I represent an 39Enum39 in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I m mainly a C# developer, but I m currently working on a project in Python.

How can I represent the equivalent of an Enum in Python?

Answers

https://pypi.python.org/pypi/enum34 https://pypi.python.org/pypi/enum34

http://stackoverflow.com/a/25982264/57461 http://stackoverflow.com/a/25982264/57461

    • To use enum34, do $ pip install enum34
    • To use aenum, do $ pip install aenum

Installing enum (no numbers) will install a completely different and incompatible version.


from enum import Enum     # for enum34, or the stdlib version
# from aenum import Enum  # for the aenum version
Animal = Enum( Animal ,  ant bee cat dog )

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

or equivalently:

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

In earlier versions, one way of accomplishing enums is:

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

which is used like so:

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

You can also easily support automatic enumeration with something like this:

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

and used like so:

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

Support for converting the values back to names can be added this way:

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)

This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn t exist. With the first example:

>>> Numbers.reverse_mapping[ three ]
 THREE 

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils