__getitem__ method on (meta)classes

Ron Garret rNOSPAMon at flownet.com
Tue Mar 15 11:51:50 EST 2005


In article <42370fd0.857233857 at news.oz.net>,
 bokr at oz.net (Bengt Richter) wrote:

> On Mon, 14 Mar 2005 23:44:46 -0700, Steven Bethard <steven.bethard at gmail.com> 
> wrote:
> 
> >Ron Garret wrote:
> >> What I'm really trying to do is to create enumerated types such that if:
> >> 
> >> e1 = enum(lst) and v = e1(x)
> >> 
> >> then
> >> 
> >> (x in lst) and (e1[v] == x)
> >
> >Use a class with __call__ and __getitem__:
> >
> >py> class enum(object):
> >...     def __init__(self, vals):
> >...         self.vals = vals
> >...     def __call__(self, val):
> >...         return self.vals.index(val)
> >...     def __getitem__(self, index):
> >...         return self.vals[index]
> >...
> >py> lst = 'abcd'
> >py> x = 'b'
> >py> e1 = enum(lst)
> >py> v = e1(x)
> >py> (x in lst) and (e1[v] == x)
> >True
> 
> For that, why not just
> 
>  class enum(list):
>     def __call__(self, val): return self.index(val)

Because I forgot to mention that I also want type(v)==e1.  (Enum is a 
small part of a static typing system for automatically generating 
database schema from data models.)

rg



More information about the Python-list mailing list