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]
Julien Le Coupanec
  • 7,195
  • 6
  • 47
  • 60
  • 5
    [`setattr(self, key, value)`](https://docs.python.org/2/library/functions.html#setattr)? – dhke Jul 14 '17 at 18:58
  • 2
    I'm not sure what you're doing, but this doesn't look like a good idea to me. You usually want to [keep data out of your variable names](https://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) – That1Guy Jul 14 '17 at 19:01

2 Answers2

3

Use setattr():

def update(self, **kwargs):
    for key, value in kwargs.items():
        setattr(self, key, value)
dhke
  • 14,408
  • 2
  • 37
  • 56
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)
Thierry Lathuille
  • 22,718
  • 10
  • 38
  • 45