__setitem__ puzzle

Bjorn Pettersen BPettersen at NAREX.com
Mon Apr 21 17:59:18 CEST 2003


> From: Anton Vredegoor [mailto:anton at vredegoor.doge.nl] 
> 
> I have subclassed the builtin list type to accept tuples for indexing.
> I am just experimenting with the code to see what I can do with it, so
> asking for what the code will be used for in order to provide a better
> way to do it will be answered with 'ni' :-)
> 
> There's a problem with __setitem__ however. What's the proper way to
> write this class?
> 
> Anton
> 
> class tlist(list):
>     
>     def __getitem__(self,x):
>         y = self[:]
>         for z in x:
>             y = y[z]
>         return y
> 
>     def __setitem__(self,x,val):
>         y = self[:]
          root = y         # save 1st level mutable items
>         for z in x[:-1]:
>             y = y[z]
>         y[x[-1]] = val
          self[:] = root   # update 1st level mutable items

[...]
>     L[(1,1,0)] = 0

Is equivalent to L[1,1,1], and you can also do fun things like L[1:2,
4:9]. Advice: special case one tuples (L[n]).

-- bjorn





More information about the Python-list mailing list