How do you control _all_ items added to a list?

X

Xif

Hi

I want to have control over all items added to a list.

The first attempt was to subclass list and override its .append()
method.

Problem is, there are plenty of other ways the list can have items
added to it - e.g. extend, insert - and theyr'e not at all affected by
the changes I made to append.

Is there some "base" item-adding method that all other item-adding
methods use, so I can override it and have the changes affect all
item-adding functions?

Thanks,
Xif
 
F

Fuzzyman

Xif said:
Hi

I want to have control over all items added to a list.

The first attempt was to subclass list and override its .append()
method.

Problem is, there are plenty of other ways the list can have items
added to it - e.g. extend, insert - and theyr'e not at all affected by
the changes I made to append.

Is there some "base" item-adding method that all other item-adding
methods use, so I can override it and have the changes affect all
item-adding functions?

If you subclass list then you will need to override all methods that
can set items. This is because the built in methods work directly with
the internal structure and are implemented in C. It's a bit of a
pain... but not that much.

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml
 
X

Xif

Quoting Fuzzyman:

"If you subclass list then you will need to override all methods that
can set items."


Overiding all those methods is too much of an effort. I don't really
need them.

I'll just have an object that uses a list internally, and define only
the two methods I really need: extend() and getItems().

That way I retain full control over what goes into the private
obj._list, without the superfluous work of overriding all those methods
I don't really need.

Thanks for your help,
Xif
 
N

Nick Coghlan

Xif said:
Overiding all those methods is too much of an effort. I don't really
need them.

Hmm, it might be nice if there was a UserList.ListMixin that was the counterpart
to UserDict.DictMixin that let's you provide the full dictionary API with just
__getitem__, __setitem__, __delitem__ and keys()

With an appropriate ListMixin, providing the first three methods would suffice
to support the full list API.

Cheers,
Nick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top