Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pickle got acycle recursion with getattr?

class Test(object):
    def __init__(self, a):
        self.a = a

    def __getattr__(self, name):
        return getattr(self.a, name)

from pickle import loads, dumps
loads(dumps((Test(something),)))

I got:

      7     def __getattr__(self, name):
----> 8         return getattr(self.a, name)

RuntimeError: maximum recursion depth exceeded

any hint?

I can fix this by changing the code like:

if 'a' in self.__dict__:
    return getattr(self.a, name)

but I don't want to. Any better solution?

Thank you

like image 622
Jiangfan Du Avatar asked Nov 02 '22 02:11

Jiangfan Du


1 Answers

I'd use getattr() instead of __getattr__. This would be equivalent to calling getattr(Test(a).a, name). This first turns to a.__getattribute__ and if that fails then to a.__getattr__

class Test(object):
    def __init__(self, a):
        self._a = a

    def __getattr__(self, name):
        a = object.__getattribute__(self, '_a')
        return getattr(a, name)
like image 146
kerma Avatar answered Nov 15 '22 04:11

kerma