Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare python enum without value using name instead

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
like image 438
Joey Baruch Avatar asked Jun 27 '26 01:06

Joey Baruch


1 Answers

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

like image 158
Jonathan1609 Avatar answered Jun 28 '26 16:06

Jonathan1609