'Does Python's enum class use partial string matching?

I have an enum class representing time periods, but i'd like the have two different names for the same mapping

class TimePeriod(enum.IntEnum):
    DAILY = 1
    MONTH = 2
    MONTHLY = 2

However, when I access MONTH or MONTHLY I get the MONTH type as shown below:

TimePeriod.MONTH
returns: <TimePeriod.MONTH: 2>

TimePeriod.MONTHLY
returns: <TimePeriod.MONTH: 2>

Is Python's enum code using partial matching for the enumeration? This happens when I reverse the order of MONTH and MONTHLY in the class definition as well.



Solution 1:[1]

Enums are unique -- not by name, but by value. When a name for a value appears more than once, the name first seen is considered the canonical name for that value, and all other names for that same value are aliases.

From the docs:

Having two enum members with the same name is invalid:

>>>
>>> class Shape(Enum):
...     SQUARE = 2
...     SQUARE = 3
...
Traceback (most recent call last):
...
TypeError: Attempted to reuse key: 'SQUARE'
However, two enum members are allowed to have the same value.
Given two members A and B with the same value (and A defined
first), B is an alias to A. By-value lookup of the value of A
and B will return A. By-name lookup of B will also return A:

>>>
>>> class Shape(Enum):
...     SQUARE = 2
...     DIAMOND = 1
...     CIRCLE = 3
...     ALIAS_FOR_SQUARE = 2
...
>>> Shape.SQUARE
<Shape.SQUARE: 2>
>>> Shape.ALIAS_FOR_SQUARE
<Shape.SQUARE: 2>
>>> Shape(2)
<Shape.SQUARE: 2>

Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ethan Furman