1

I'm working with Python's Enum classes (in Python 3.9), and trying to combine a couple of things from their documentation. The "Planet" example class demonstrates a tuple (mass,radius) as the value of the enum members, and also setting additional member attributes based on that as the values are passed to an overridden __init__() method. However, the "value" of the enum members winds up being that tuple. The AutoName class shows using the enum.auto() helper function and an overridden _generate_next_value_() method to use the member's name as the value. And in general, overriding the __new__() method seems to be the only way to set the value attribute of a member. I'm having trouble combining these three things.

What I'd like is something like Planet, except where the "value" is changed to "name", as in AutoName(), so that Planet.MERCURY is "MERCURY", not the tuple. But in an override of __new__(), there seems to be no way to know what the "name" of the member being created is, so you can't set "value" to it. And with "auto()", there seems to be no way to provide additional values, like the (mass, radius) info from Planet. I'd hoped to do something like this (assuming the existence of the AutoName class):

class Planet(AutoName): MERCURY = auto(3.303e+23, 2.4397e6) # doesn't work VENUS = (auto(), 4.869e+24, 6.0518e6) # doesn't work 

Is there a way to combine the tuple for the enum value with some way of also changing the member value, as auto() does?

1 Answer 1

2

It is not possible using the stdlib Enum, but is possible using the aenum1 library:

from aenum import Enum class AutoName(Enum): def _generate_next_value_(name, start, count, last, *args, **kwds): return (name, ) + args class Planet(AutoName): _init_ = 'value mass radius' MERCURY = 3.303e+23, 2.4397e6 VENUS = 4.869e+24, 6.0518e6 

_init_ serves two purposes:

  • specifies what attributes to save the given values to
  • if more attributes are specified than given, call _generate_next_value_ in an attempt to create the missing values

--

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.