ListMixin (WAS: How do you control _all_ items added to a list?)

Raymond Hettinger vze4rx4y at verizon.net
Tue Mar 1 20:47:50 EST 2005


[Nick Coghlan]
>  > Hmm, it might be nice if there was a UserList.ListMixin that was the
>  > counterpart to UserDict.DictMixin

[Steven Bethard]
> I've thought this occasionally too.  One of the tricky issues though is
> that often you'd like to define __getitem__ for single items and have
> ListMixin add the code for slices.  I haven't figured out how to do this
> cleanly yet...

All that is needed is a helper function and a two line idiom for calling it from
inside __getitem__:

def sliceit(self, sliceobj):
    return [self[i] for i in xrange(*sliceobj.indices(len(self)))]

class AlphaList:
    def __getitem__(self, i):
        if isinstance(i, slice):
            return sliceit(self, i)
        return chr(i+64)
    def __len__(self):
        return 26

a = AlphaList()
print a[1], a[2], a[5]
print a[2:5]





More information about the Python-list mailing list