Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cleanest way to set up an enumeration in Python? [duplicate]

I'm relatively new to Python and I was interested in finding out the simplest way to create an enumeration.

The best I've found is something like:

(APPLE, BANANA, WALRUS) = range(3)

Which sets APPLE to 0, BANANA to 1, etc.

But I'm wondering if there's a simpler way.

like image 991
bob Avatar asked Jun 14 '15 06:06

bob


People also ask

Can enum have duplicate values Python?

CA1069: Enums should not have duplicate values.

Should enums be capitalized Python?

By convention, enumeration names begin with an uppercase letter and are singular. The enum module is used for creating enumerations in Python. Enumerations are created with the class keyword or with the functional API.

Should I use enum in Python?

Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.


2 Answers

Enums were added in python 3.4 (docs). See PEP 0435 for details.

If you are on python 2.x, there exists a backport on pypi.

pip install enum34

Your usage example is most similar to the python enum's functional API:

>>> from enum import Enum
>>> MyEnum = Enum('MyEnum', 'APPLE BANANA WALRUS')
>>> MyEnum.BANANA
<MyEnum.BANANA: 2>

However, this is a more typical usage example:

class MyEnum(Enum):
    apple = 1
    banana = 2
    walrus = 3

You can also use an IntEnum if you need enum instances to compare equal with integers, but I don't recommend this unless there is a good reason you need that behaviour.

like image 103
wim Avatar answered Oct 29 '22 15:10

wim


You can use this. Although slightly longer, much more readable and flexible.

from enum import Enum
class Fruits(Enum):
    APPLE = 1
    BANANA = 2
    WALRUS = 3

Edit : Python 3.4

like image 32
Utsav T Avatar answered Oct 29 '22 16:10

Utsav T