7

How can I set an object property given its name in a string? I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this:

for entry in src_dict:
      if entry.startswith('can_'):
          tgt_obj[entry] = src_dict_profile[entry]
0

3 Answers 3

25
setattr(some_object, 'some_attribute', 42)
2
  • 5
    Please, no semicolons. :-D
    – smitelli
    Feb 16, 2018 at 18:59
  • 2
    This doesn't use the @property.setter function though does it... how would you set the property through that?
    – jscul
    Jan 18, 2019 at 0:07
7

Sounds like you're looking for setattr.

Example:

for entry in src_dict:
      if entry.startswith('can_'):
          setattr(tgt_obj, entry, src_dict_profile[entry])
1

On objects that have "dict" property

if "__dict__" in dir(obj):

you may do fun things like:

obj.__dict__.update(src_dict)

Not the answer you're looking for? Browse other questions tagged or ask your own question.