Search code examples
pythonpython-3.xsetattr

Clean way to disable `__setattr__` until after initialization


I've written the following wrapper class. I want to define __setattr__ such that it redirects all attributes to the wrapped class. However, this prevents me from initializing the wrapper class. Any elegant way to fix this?

class Wrapper:
    def __init__(self, value):
        # How to use the default '__setattr__' inside '__init__'?
        self.value = value

    def __setattr__(self, name, value):
        setattr(self.value, name, value)

Solution

  • You are catching all assignments, which prevents the constructor from assigning self.value. You can use self.__dict__ to access the instance dictionary. Try:

    class Wrapper:
        def __init__(self, value):
            self.__dict__['value'] = value
    
        def __setattr__(self, name, value):
            setattr(self.value, name, value)
    

    Another way using object.__setattr__:

    class Wrapper(object):
        def __init__(self, value):
            object.__setattr__(self, 'value', value)
    
        def __setattr__(self, name, value):
            setattr(self.value, name, value)