1

I'm looking for a way to update an attribute programmatically (especially when inside an update() function of an SQLAlchemy class)

def update(self, **kwargs):
    for kwarg in kwargs:
        setattribute(self, kwarg, kwargs[kwarg])

This does not seem to work, neither this:

def update(self, **kwargs):
    for kwarg in kwargs:
        self[kwarg] = kwargs[kwarg]
2

2 Answers 2

3

Use setattr():

def update(self, **kwargs):
    for key, value in kwargs.items():
        setattr(self, key, value)
Sign up to request clarification or add additional context in comments.

Comments

1

kwargs is a dict, you can iterate on its keys and values with items():

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.