list inheritance or delegation?

george young gry at ll.mit.edu
Tue Mar 16 15:51:15 EST 2004


[python 2.3.3, x86 linux]
I need an object that behaves much like a list, but has some
additional features.  It seems that I can do this either by
inheriting from type list, or by emulating list by defining
__len__, __getitem__, and maybe a bunch of  other methods.  Thirdly,
I could inherit from UserList, but that's deprecated now.

Inheriting from list would save me implementing a bunch of methods
that I might want.  But if I inherit from list, how do I get access
to the data?  E.g., I need a customized 'setitem' method that does
the insert and then does some other things too.  With UserList, I could:

class mylist(UserList):
   def __setitem__(self,i,y):
	self.dostuff(y)
	self.data[i]=y

but when inheriting from 'list', I'm not sure how to do this.

I couldn't find anything in the docs about inheriting from builtin
types, though it seems to be an encouraged practice.  It seems like if
one is encouraged to inherit from builtins, there needs to be at least
a concise description of the 'inheritable api' for each such type.
E.g. does __init__ or __new__ handle initial values.  Maybe I'm just
missing something obvious...
	
So, I'm asking:
1) what are the issues/tradoffs between inheriting from list and emulating
   it with my own methods referencing a list data member.

2) how do I get enough access to list's data to do the inheritance.

3) I'm whining about lack of documentation for #2.

Thanks,
   George Young



More information about the Python-list mailing list