Class.__class__ magic trick help

Massimo DiPierro massimo.dipierro at gmail.com
Tue Aug 21 10:42:11 EDT 2012


Thanks again Oscar. I cannot do that. I have tight constraints. I am not at liberty to modify the code that uses the class. The exposed API cannot change including a.x, dict(a), is isinstance(a,dict).

My goal it so change the definition of this class to make it faster.

Where is in the Python source code is the casting to dict defined? Where can I try understand what it does?

Massimo


On Aug 21, 2012, at 9:14 AM, Oscar Benjamin wrote:

> On 21 August 2012 14:50, Massimo Di Pierro <massimo.dipierro at gmail.com> wrote:
> Hello Oscar,
> 
> thanks for your help but your proposal of adding:
> 
> def __setitem__(self,key,value):
>    self.__dict__[key] = value
>    dict.__setitem__(self, key, value)
> 
> does not help me.
> 
> What I have today is a class that works like SlowStorage. I want to
> replace it with NewStorage because it is 10x faster. That is the only
> reason. NewStorage does everything I want and all the APIs work like
> SlowStorage except casting to dict.
> 
> By defining __setitem__ as you propose, you solve the casting to dict
> issue but you have two unwanted effects: each key,value is store twice
> (in different places), accessing the elements becomes slower the
> SlowStprage which is my problem in the first place.
> 
> The issue for me is understanding how the casting dict(obj) works and
> how to change its behavior so that is uses methods exposed by obj to
> do the casting, if all possible.
> 
> Then you have two options:
> 1) subclass object instead of dict - you're not using any of the features of the dict superclass and the fact that it is a superclass is confusing the dict() constructor.
> 2) use a different "cast" e.g. d = dict(a.items())
> 
> Oscar

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120821/c44c716c/attachment.html>


More information about the Python-list mailing list