2

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.

colidyre
  • 4,170
  • 12
  • 37
  • 53
Anab
  • 265
  • 1
  • 9

2 Answers2

2

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'>]
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
0

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.

colidyre
  • 4,170
  • 12
  • 37
  • 53
  • 1
    I saw the post you link, I hoped that there was some kind of magic available for enums. Too bad that there isn't! – Anab Aug 27 '20 at 17:30