Subclassing list the right way?

Kirk Strauser kirk.strauser at gmail.com
Fri Apr 25 10:03:26 EDT 2008


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



More information about the Python-list mailing list