Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use enum in Python

📅 2013-May-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

Python 3

Python 3 has support for enumeration in the standard library.

from enum import Enum

class Color(Enum):
    Red   = 1
    Green = "green"
    Blue  = 3
    AnotherBlue = 3  # Values may not be unique

c = Color.Green
c = Color("green")  # Same as setting to Color.Green
from enum import Enum, unique

@unique
class Colors(Enum):
    Red   = "red"
    Green = "green"
    Blue  = "blue"

Python 2

Python 2.x does not have enumeration type. You can install the backported Python 3 enum for Python 2 easily from here:

$ sudo pip install enum34

Tried with: Python 3.6.8, Python 2.7.6 and Ubuntu 18.04