I am trying to write an "enum class" in python. A slight nuisance I am currently experiencing is the inability to define enum values inside the enum class. That is, I can do this:
class Fruit:
def __init__(self, name):
self.name = name
class Fruits(Enum):
Apple = Fruit("apple")
But I would like to do this, or a similarly legible equivalent:
class Fruit(Enum):
def __init__(self, name):
self.name = name
Apple = Fruit("apple")
Unfortunately, I am getting the following error: name 'Fruit' is not defined
What are the rules of visibility in such a case? Are there any little-known Python tricks that could help me? I would prefer something that is possible to write in the metaclass of Enum, since that would make usage less cumbersome for the user.
class
has not finished being defined until you reach the end of it's blockFruit.Apple = Fruit("apple")
to create an instance and store it as a class attribute.__iter__()
support, so I can writefor fruit in Fruits
. As for addingFruit.Apple =
after the class definition, it's doable and not-that-bad. I'll look for something better, maybe I can find it :)