Subclassing list the right way?

Virgil Dupras hardcoded.software at gmail.com
Fri Apr 25 11:23:12 EDT 2008


On Apr 25, 4:03 pm, Kirk Strauser <kirk.strau... at gmail.com> wrote:
> I want to subclass list so that each value in it is calculated at call
> time.  I had initially thought I could do that by defining my own
> __getitem__, but 1) apparently that's deprecated (although I can't
> find that; got a link?), and 2) it doesn't work.
>
> For example:
>
> >>> class Foo(list):
>
> ...     def __getitem__(self, index):
> ...             return 5
> ...>>> a = Foo([1, 2, 3, 4, 5])
> >>> print a
> [1, 2, 3, 4, 5]
> >>> print a[2:4]
> [3, 4]
> >>> print a[3]
>
> 5
>
> I first expected that to instead behave like:
>
> >>> print a
> [5, 5, 5, 5, 5]
> >>> print a[2:4]
>
> [5, 5]
>
> Is there a "right" way to do this?
> --
> Kirk Strauser

I'm not totally sure, but I think you have to implement __getslice__
as well, even if it is a deprecated magic function. My guess for this
is that list implements __getslice__ and when you ask for a slice,
Python checks for __getslice__ first, and then, if you don't have it,
calls __getitem__. And since list has it, it's what is called.

As for "print a", you have to override __str__ and __repr__ too.

As a side note, the second argument to __getitem__ is not index, it's
key, because this argument can either be an int index or a slice()
object.



More information about the Python-list mailing list