0

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>
1
  • Would the getattr function suffice? Commented Mar 15, 2018 at 16:17

2 Answers 2

1

With setattr:

for name in ['command', 'options', 'library']:
    try:
        value = data_dict[name]
    except KeyError:
        pass
    else:
        setattr(self, name, value)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.