7

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.

5
  • 1
    The metaclass for Enum is not shown, since I think it's pretty irrelevant.
    – Liosan
    Commented Apr 30, 2013 at 11:08
  • that's because the class has not finished being defined until you reach the end of it's block
    – jamylak
    Commented Apr 30, 2013 at 11:16
  • 1
    After the class definition you can do a Fruit.Apple = Fruit("apple") to create an instance and store it as a class attribute.
    – martineau
    Commented Apr 30, 2013 at 11:21
  • The metaclass for Enum is not shown because it's irrelevant, yet you want to know how to modify it to solve your problem. What does the unshown metaclass currently do?
    – martineau
    Commented Apr 30, 2013 at 11:26
  • @martineau The metaclass adds __iter__() support, so I can write for fruit in Fruits. As for adding Fruit.Apple = after the class definition, it's doable and not-that-bad. I'll look for something better, maybe I can find it :)
    – Liosan
    Commented Apr 30, 2013 at 11:44

1 Answer 1

1

You could make a metaclass that did something simple like this:

class MetaEnum(type):
    def __new__(cls, class_name, parents, attrs):
        def __init__(self, name=None):
            if name is not None: self.name = name
        attrs['__init__'] = __init__
        Klass = type.__new__(cls, class_name, parents, attrs)
        if 'instances' in attrs:
            for name in attrs['instances']:
                setattr(Klass, name.capitalize(), Klass(name))
            del Klass.instances # clean up
        return Klass

class Fruit(object):
    __metaclass__ = MetaEnum
    instances = ('apple', 'banana', 'cranberry')

for attr_name in dir(Fruit):
    if not attr_name.startswith('_'):
        attr = getattr(Fruit, attr_name)
        if type(attr) is Fruit:
            print('Fruit.{}, is a Fruit named {}'.format(attr_name, getattr(attr, 'name')))
        else:
            print('Fruit.{}, is a {}'.format(attr, type(attr)))

Output:

Fruit.Apple, is a Fruit named apple
Fruit.Banana, is a Fruit named banana
Fruit.Cranberry, is a Fruit named cranberry
3
  • Not bad, if I read it correctly it does what I wanted. I didn't think about this route. Pity on the syntax, I'll work on it a bit... Definitely +1.
    – Liosan
    Commented Apr 30, 2013 at 11:47
  • You want instances? OK, see my updated answer to your updated question.
    – martineau
    Commented Apr 30, 2013 at 12:03
  • Re: the syntax, if you define __metaclass__ = MetaEnum at the global module-level it will become the default and apply to any class definitions that follow it (that don't specify their own).
    – martineau
    Commented Apr 30, 2013 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.