Search code examples
pythonclasssetattr

using setattr within a class method to sel something on self


When doing this

class Example:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def update(self, **kwargs):
        for key, value in kwargs.items():
            getattr(self, key)
            setattr(self, key, value)

.. the update function won't update an instance of this class. I've tried self.__setattr__(key, value) and object.__setattr__(self, key, value) and even tried eval(f"self.{key}={repr(value)}") which threw an error!

UPDATE: The code does work.initially I had coded self.__setattr__(key, value). Microsoft vscode ( running on linux ) somehow caches things, for a very very long time and despite rotating through several changes of code didn't show any change in the test results i was running. After taking a break to ask this question I ran the answer code below, then reverted to setattr and everything worked from there. really annoyed with that!!


Solution

  • Use __dict__ as a shortcut:

    class Example:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        def update(self, **kwargs):
            # you need to do some checks here (if attribute exists or not)
            self.__dict__.update(kwargs)
    
    
    e = Example(1, 2)
    print(e.__dict__)
    
    e.update(a=3, b=4)
    print(e.__dict__)
    

    Output:

    {'a': 1, 'b': 2}
    {'a': 3, 'b': 4}