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.
CA1069: Enums should not have duplicate values.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With