__setitem__ puzzle

Anton Vredegoor anton at vredegoor.doge.nl
Mon Apr 21 09:02:31 EDT 2003


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[:]
        for z in x[:-1]:
            y = y[z]
        y[x[-1]] = val

def test():
    L = tlist(['aa',['bb',['cc','dd'],'ee'],'ff',['gg']])
    indices = [(0,), (1,), (1, 0), (1, 1), (1, 1, 0),
                (1, 1, 1), (1, 2), (2,), (3,), (3, 0)]
    for x in indices:
        print L[x]
    print
    L[(1,1,0)] = 0
    print L
    L[(1,1)] = 0
    print L
    #this doesn't work
    L[(1,)] = 0
    print L

if __name__=='__main__':
    test()





More information about the Python-list mailing list