7

Is there an analog of setattr() that allows for appending an arbitrary list property of an instantiated class object? If not, is there a recommended way of doing so?

This is a trivialized version of what I'm doing currently:

foo = SomeClass()
...
attr = "names"
value = "Eric"
values = getattr(foo, attr)
values.append(value)
setattr(foo, attr, values)

This seems clunky and inefficient.

Edit: this assumes that foo.names (or whatever arbitrary value might be assigned to the attr variable) is in fact a list.

1 Answer 1

15

The setattr call is redundant, if foo.names is indeed a list (if it's something else, could you please clarify?). getattr(foo, attr).append(value) is all you need.

Sign up to request clarification or add additional context in comments.

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.