[Tutor] custom container subclassing list-- slices are lists!?

John Fouhy john at fouhy.net
Mon Aug 21 23:52:41 CEST 2006

On 22/08/06, Marcus Goldfish <magoldfish at gmail.com> wrote:
> Second, I think I found a partial answer in the Feb 22, 2005 tutor thread
> http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2502290.
>  To preserve type, I need to override some special functions.  In the case
> of slicing, I need to override with something like this:
> def __getslice__(self, i, j):
>    return MyFoo(list.__getslice__(self, i, j))

__getslice__ is apparantly deprecated these days; you should override
__getitem__ instead.
(see the links I posted in my last message)

> This seems straightforward, but raises other questions: what other functions
> should I override, e.g., __add__, __radd__?  Is there a preferred pythonic
> way to creating a custom list container?

Hmm, if you were talking about dicts, I would have said "Use
UserDict.DictMixin".  But there doesn't seem to be a
UserList.ListMixin.  There's a community one here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440656  that
might work for you, but I haven't used it myself.

> Finally, should I slice-copy my input list, inlist, to prevent side effects,
> or is this handled by list?

Should be handled by the list.  For instance if x is a list, then
list(x) is a copy of x (y=list(x) is equivalent to y=x[:]).  But you
should be able to test this easily enough..


More information about the Tutor mailing list