Ron Garret wrote:
And the code I ended up with is:

# Inheriting from type, not object, is the key:
class enum_metaclass(type):
  def __getitem__(self, index):
    return self.vals[index]

def enum(vals):
  class enum(object):
    __metaclass__ = enum_metaclass
    def __init__(self, val):
      try:
        self.val = type(self).vals.index(val)
      except:
        raise TypeError, "%s is not a valid %s" % (val, type(self))
  enum.vals = vals
  return enum

A good example of why 99.9% of people don't need metaclasses. See my solution using __call__ in the other post.


Note that there's no __iter__ method anywhere! It makes an interesting little puzzle to figure out why this works. (It totally blew me away when I first tried it. Took me about five minutes of head scratching to figure it out.)

Best to add an __iter__ if you want one. The __getitem__ protocol is basically deprecated though it works for backwards compatibility.


STeVe
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to