Ray Salemi
Ray Salemi

Reputation: 5903

Setting attributes by attribute name in Python

I've got this somewhat ugly code writing to a bunch of properties. It seems I should be able to loop through a list to do this. How would I loop through ['command','options','library'] and set the associated property?

    <snip>

    try:
        self.command = data_dict['command']
    except KeyError:
        pass

    try:
        self.options = data_dict['options']
    except KeyError:
        pass

    try:
        self.library = data_dict['library']
    except KeyError:
        pass

   <snip>

Upvotes: 0

Views: 42

Answers (2)

Jim Wright
Jim Wright

Reputation: 6058

You can use setattr to set an attribute with a dynamic name.

In my opinion it is cleaner check if the key exists rather than handling the KeyError.

for name in ['command', 'options', 'library']:
    if name in data_dict:
        setattr(self, name, value)

Upvotes: 1

Jean-Paul Calderone
Jean-Paul Calderone

Reputation: 48335

With setattr:

for name in ['command', 'options', 'library']:
    try:
        value = data_dict[name]
    except KeyError:
        pass
    else:
        setattr(self, name, value)

Upvotes: 1

Related Questions