[Python-Dev] python2.7 infinite recursion when loading pickled object

Akira Li 4kir4.1i at gmail.com
Mon Aug 11 15:01:31 CEST 2014

"Schmitt  Uwe (ID SIS)" <uwe.schmitt at id.ethz.ch> writes:

> I discovered a problem using cPickle.loads from CPython 2.7.6.
> The last line in the following code raises an infinite recursion
>     class T(object):
>         def __init__(self):
>             self.item = list()
>         def __getattr__(self, name):
>             return getattr(self.item, name)
>     import cPickle
>     t = T()
>     l = cPickle.dumps(t)
>     cPickle.loads(l)
> Is this a bug or did I miss something ?

The issue is that your __getattr__ raises RuntimeError (due to infinite
recursion) for non-existing attributes instead of AttributeError. To fix
it, you could use object.__getattribute__:

  class C:
    def __init__(self):
        self.item = []
    def __getattr__(self, name):
        return getattr(object.__getattribute__(self, 'item'), name)

There were issues in the past due to {get,has}attr silencing
non-AttributeError exceptions; therefore it is good that pickle breaks
when it gets RuntimeError instead of AttributeError.


More information about the Python-Dev mailing list