Search code examples
pythongetattr

Using the __dict__ attribute in __getattr__


Here is a simple class with a customized __getattr__ implementation:

class Wrapper(object):
    def __init__(self, obj):
        self.obj = obj

    def __getattr__(self, name):
        func = getattr(self.__dict__['obj'], name)
        if callable(func):
            def my_wrapper(*args, **kwargs):
                print "entering"
                ret = func(*args, **kwargs)
                print "exiting"
                return ret
            return my_wrapper
        else:
            return func

What I don't understand here is why getattr(self.__dict__['obj'], name) is used instead of getattr(self.obj, name) which is more concise?

Because as far as I can see what self.__dict__['obj'] does is invoke the value of self.obj. May it have anything to do with backward compatibility?


Solution

  • I believe, the reason for this code to exist – author tried to evade endless recursion loop – to not trigger __getattr__ by self.obj