Python enum multiple values | Example code

Use MultiValueEnum to get enum multiple values in Python. You have to install and import aenum library and this is the easiest way.

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

Alternative way 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

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.