__getitem__ method on (meta)classes

Steven Bethard steven.bethard at gmail.com
Tue Mar 15 02:05:28 EST 2005


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



More information about the Python-list mailing list