overriding __getitem__ for a subclass of dict
Steve Howell
showell30 at yahoo.com
Sun Nov 15 19:58:43 EST 2009
On Nov 15, 4:03 pm, Christian Heimes <li... at cheimes.de> wrote:
> Steve Howell wrote:
> > Does anybody have any links that points to the rationale for ignoring
> > instance definitions of __getitem__ when new-style classes are
> > involved? I assume it has something to do with performance or
> > protecting us from our own mistakes?
>
> Most magic methods are implemented as descriptors. Descriptors only
> looked up on the type to increase the performance of the interpreter and
> to simply the C API. The same is true for other descriptors like
> properties. The interpreter invokes egg.__getitem__(arg) as
> type(egg).__getitem__(egg, arg).
>
Is the justification along performance lines documented anywhere?
> > So now I am still in search of a way to hook into calls to foo[bar]
> > after foo has been instantiated. It is all test code, so I am not
> > particularly concerned about safety or future compatibility. I can do
> > something really gross like monkeypatch Foo class instead of foo
> > instance and keep track of the ids to decide when to override
> > behavior, but there must be a simpler way to do this.
>
> Try this untested code:
>
> class Spam(dict):
> def __getitem__(self, key):
> getitem = self.__dict__.get("__getitem__", dict.__getitem__)
> return getitem(self, key)
> [...]
Not sure how this helps me, unless I am misunderstanding...
It is the futility of writing lowercase_spam.__getitem__ that is
setting me back. For my use case I do not want to override
__getitem__ for all Spam objects, nor do I even have the option to
modify the Spam class in some cases.
More information about the Python-list
mailing list