0

I'm writing a custom EnumMeta class in Python 2.7 that will collect enum keys and values from some class and augment that class with some additional fields.

class EnumMeta(type):
    def __init__(cls, name, bases, props):
        cls.__all_values__ = [...] # collect all interesting properties

    def __contains__(cls, value):
        return value in cls.__all_values__

class TheFellowshipOfTheRing(object):
    __metaclass__ = EnumMeta

    FRODO = 'Frodo Baggins'
    SAM = 'Samwise "Sam" Gamgee'
    MERRY = 'Meriadoc "Merry" Brandybuck'
    PIPPIN = 'Peregrin "Pippin" Took'
    GANDALF = 'Gandalf the Grey'
    ARAGORN = 'Aragorn (Strider)'
    LEGOLAS = 'Legolas'
    GIMLI = 'Gimli'
    BOROMIR = 'Boromir'

print 'Gandalf the Grey' in TheFellowshipOfTheRing
@ True
print 'Saruman' in TheFellowshipOfTheRing
@ False

I'm wondering if implementing container-specific functions, such as __contains__, on a metaclass is a dangerous thing to do, and if so, why?

LavaScornedOven
  • 737
  • 1
  • 11
  • 23
  • 1
    No, that's how Python 3's `Enum` class does it: http://hg.python.org/cpython/file/default/Lib/enum.py#l226. Instead of writing your own Enum class, you may want to use a backported version of the one from 3.4: https://pypi.python.org/pypi/enum34/ – Blender Mar 11 '14 at 01:01
  • This is just the gist of the implementation, but I have really specific requirements where 3.4 enum doesn't quite fit. But great hint. Thnx! – LavaScornedOven Mar 11 '14 at 01:06

0 Answers0