3

Is there any way in python to declare an enum's variables without values?

The syntax that works:

from enum import Enum class Color(Enum): Red = 'Red' Blue = 'Blue' Green = 'Green' 

Since for this case the enum values are the same as the variable names, I'd like to avoid duplication.

Something like this maybe:

from enum import Enum class Color(Enum): Red Blue Green 

1 Answer 1

3

This is why enum.auto() is a thing, so you don't need to write values explicitly.

from enum import Enum, auto class Color(Enum): Red = auto() Blue = auto() Green = auto() 

You can also do print(Color.Red.name) to retrieve the name of the member :D

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

5 Comments

This however will provide numeric sequential values for the enumerations, not reflect their name.
@jsbueno why would you need enums to reflect their names? That's not how enums work, you use enum for example to state mode, or to compare stuff, like if mode == Modes.STANDBY etc.. you don't use their names at all, just as identifiers.
It is not me, it is what the OP asked for. But yes, soemtimes you just need this: a pickable, human readable , distinguished value that can be typed unquoted in text. It is mote of a "name spaced constants" than an Enum, but it is very useful. To the point some languages have this feature built in the syntax itself.
@jsbueno then you can do print(Color.Red.name) or any Color.*.name.
Still hope that in a near future we can have a version of python or Enum where you can avoid '= ...' similar to what is provided in the question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.