Pythonic syntax for adding class object list property

Is there an analogue setattr()that allows you to add an arbitrary property of a list of an object of an instance of a class? If not, is this recommended?

This is a trivial version of what I am currently doing:

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

It seems awkward and inefficient.

Edit: this assumes that foo.names (or any other arbitrary value can be assigned to the attr variable) is actually a list.

+5
source share
1 answer

The call is setattrredundant if it foo.namesreally is a list (if it is something else, could you clarify?). getattr(foo, attr).append(value)- that’s all you need.

+12
source

All Articles