5
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

sshashank124
  • 31,495
  • 9
  • 67
  • 76
Jiangfan Du
  • 137
  • 1
  • 5

2 Answers2

2

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)
kerma
  • 2,593
  • 2
  • 17
  • 16
0

This should work, but I doubt it's a good idea...

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

    def __getattr__(self, name):
        a = object.__getattribute__(self, 'a')
        return a.__getattr__(a, name)

from pickle import loads, dumps
loads(dumps((Test({}))))
# <__main__.Test at 0x7f6beb8>
Matt
  • 17,290
  • 7
  • 57
  • 71