Anab
Anab

Reputation: 277

How to get the name of a value in an enum declaration?

In Python3.7.7, I would like to use the name of an Enum value in the declaration of another value of the same Enum.

My first try:

from enum import Enum
class test(Enum):
    value1 = "a"
    value2 = value1.name + "b"

This returns an AttributeError: 'str' object has no attribute 'name'. I tried using self.value1 and test.value1 instead and both return a NameError.

I could just use value2 = "value1b" but I fear that it would give me weird errors down the line if I ever change the name of value1 and forget some places instead of an immediate error because of an undefined variable.

Upvotes: 2

Views: 635

Answers (2)

colidyre
colidyre

Reputation: 4666

What you try to achieve is not simple, because you can only directly reference from a variable to the value, not vice versa.

I think the easiest solution is using Python3.8+ and using the debugging feature of f-strings (emphasis mine):

To display both the expression text and its value after evaluation, (useful in debugging), an equal sign '=' may be added after the expression.

So the code would turn into:

from enum import Enum

class test(Enum):
    value1 = "a"
    value2 = f"{value1=}".split("=")[0] + "b"

Other solutions, also working with Python3.7- can be found here. But they are more complicated to implement.

Upvotes: 0

Ethan Furman
Ethan Furman

Reputation: 69041

During Enum class creation the values are just values -- they are not converted to Enum members until the end of the class definition.

There is nothing currently in the class definition machinery to support your use-case; however, you can use the functional syntax to generate your Enum:

# some code to calculate your names and values (not shown)
# that results in
members = (('value1', 'a'),('value2', 'value1a'))
test = Enum('test', members)

Which results in:

>>> list(test)
[<test.value1: 'a'>, <test.value2: 'value1a'>]

Upvotes: 2

Related Questions