Skip to content

Python enum multiple values | Example code

  • by

Use MultiValueEnum to get enum multiple values in Python. You have to install and import aenum library and this is the easiest way. To access the values of an enumeration, you can use dot notation:

Python enum with multiple values example

Simple example code.

from aenum import MultiValueEnum


class DType(MultiValueEnum):
    float32 = "f", 8
    double64 = "d", 9


print(DType("f"))
print(DType(9))

Output:

Python enum multiple values

An alternative way to get enum multiple values

from enum import Enum


class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
            self.__class__.__name__,
            self._name_,
            ', '.join([repr(v) for v in self._all_values]),
        )


print(DType("f"))
print(DType(9))

Output:

DType.float32
DType.double64

You can also iterate over the values of an enumeration using a for loop:

from enum import Enum

class Color(Enum):
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)

for color in Color:
    print(color)

To access the values of an enumeration, you can use the .value attribute:

Color.RED.value

Do comment if you have any doubts or suggestions on this Python enum topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading