How to Implement an 'enum' in Python
Published on Aug. 22, 2023, 12:16 p.m.
In Python, you can implement an enum
using the Enum
class from the enum
module. Here’s an example:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Alternatively, you can use namedtuple
from the collections
module to define your custom data type as well. Here’s an example to create an enumeration of programming languages:
from collections import namedtuple
Language = namedtuple('Language', 'name version')
PYTHON = Language('Python', '3.9')
JAVASCRIPT = Language('JavaScript', 'ES6')
JAVA = Language('Java', '11')
You can then access the enumeration values like this:
# access an enum value by name
color = Color.RED
# iterate over all enum values
for color in Color:
print(color)
That’s how you can create and use enumerations in Python.
To create an enumeration in NumPy
To create an enumeration in NumPy, you can use the IntEnum
class from the enum
module along with a NumPy array to define the enumeration values. Here’s an example:
from enum import IntEnum
import numpy as np
class Color(IntEnum):
RED = 1
GREEN = 2
BLUE = 3
# create an array of the enumeration values
color_array = np.array([Color.RED, Color.BLUE, Color.GREEN])
# access an enumeration value by index
print(color_array[0]) # output: Color.RED
You can also use the EnumArray
class from the numpy.lib.enum
module to create an array of enumeration values. Here’s an example:
from numpy.lib.enum import EnumArray
import numpy as np
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# create an array of the enumeration values
color_array = EnumArray(['RED', 'GREEN', 'BLUE'], Color)
# access an enumeration value by index
print(color_array[0]) # output: Color.RED
Both of these methods allow you to work with enumerations in NumPy arrays.