Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum having multiple attributes as a Collection Constant

Tags:

python

enums

In a recent question (Gathering numerical data from a string input) I was wondering whether this was an acceptable answer. I thought that it would make a better question. Is this kind of representation acceptable as a constant collection? Or is it a misuse of enums? And are there any unexpected consequences from assigning the same value to the different attributes on the enum in Python?

from enum import Enum
class CreditRating(Enum):
     AAA = 0.01
     A = 0.1
     B = 0.1
creditRate = input("Please enter credit rating:")
print(CreditRating[creditRate].value)
like image 751
Rach Sharp Avatar asked Jun 04 '26 16:06

Rach Sharp


1 Answers

Enums are associations between unique names and unique values. Using a value more than once is supported, but may not be what you intended it to mean. This is explicitly covered in the documentation, see the Duplicating enum members and values section:

[T]wo 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.

The consequence is that looking up a name by value, will only return the first name:

>>> CreditRating(0.1)
<CreditRating.A: 0.1>

and when you look at B, you'll be given the A enum object:

>>> CreditRating.B
<CreditRating.A: 0.1>

If all you wanted to do was map a string to a value, I'd not use an enum, just use a dictionary:

credit_ratings = {
    'AAA': 0.01, 
    'A': 0.1,
    'B': 0.1,
}
# ...
print(credit_ratings[creditRate])

Use an enum when you need the other features such a definition provides, such as the explicit aliasing, the fact that enum values are singletons (you can use is to test for them) and that you can map both names and values back to enum objects.

like image 153
Martijn Pieters Avatar answered Jun 07 '26 22:06

Martijn Pieters