__getitem__ method on (meta)classes

Steven Bethard steven.bethard at gmail.com
Tue Mar 15 19:04:38 CET 2005

Ron Garret wrote:
> In article <Sf6dneCcy-DEGavfRVn-iw at comcast.com>,
>  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)
>>>(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)
> Yeah, except I actually left out one thing:  I also want type(v)==e1.

Why?  In Python usually you rely on duck-typing and not explicit type 
checks.  What is it that you're trying to gain by asserting type(v) == e1?


More information about the Python-list mailing list