cPickle and __getattr__

Jp Calderone exarkun at divmod.com
Mon Aug 30 02:30:48 CEST 2004


Chris Curvey wrote:
> Hi all,
> 
> I have this program
> 
> class Company:
>    def __init__(self, revenues, costs):
>       self.revenues = revenues
>       self.costs = costs
> 
>    def __getattr__(self, name):
>        if name == 'profits':
>            return self.revenues - self.costs
> 
> c = Company(100, 75)
> print c.revenues
> print c.costs
> print c.profits
> 
> import cPickle
> print cPickle.dumps(c)
> 
> Everything works fine up until the last line.  If I remove the 
> __getattr__ function, then everything works (except "print c.profits"). 
>  What is the cPickle class trying to get to that is causing my 
> __getattr__ function to be called?
> 

   Potentially lots of things.  But the problem isn't that cPickle is 
calling __getattr__, exactly.  The problem is that your __getattr__ 
isn't properly signalling non-existent attributes.  You should raise 
AttributeError instead of implicitly returning None for which there is 
no attribute.  Adding "raise AttributeError(name)" to the end of the 
definition unbreaks it enough to let pickle work.

   Jp



> -Chris
> 




More information about the Python-list mailing list