Using setattr() to append to a list attribute

918 Views Asked by At

I have an attribute of Class named tag that is a list and I have to append to this list. The attribute name and value are both str variables. I can try

setattr(obj, tag, getattr(obj,tag).append(text))

but this creates unnecessary overhead, and also returns None. Currently I am using exec to achieve the same thing. Please help me find a better way, as exec is creating some trouble with the data.

exec(f"obj.{tag}.append({text})")

EDIT: Solved as per @Anentropic's comment

1

There are 1 best solutions below

0
itismoej On

If you are mutating a mutable object, you can simply get the object with getattr and do the mutating operation.

In [1]: class A:
   ...:     mutable = []
   ...:     immutable = ()
   ...: 

In [2]: obj = A()

In [3]: getattr(obj, 'mutable').append(1)

In [4]: obj.mutable
Out[4]: [1]

But if you are trying to mutate an immutable property of an object you should do this:

In [5]: setattr(obj, 'immutable', (*getattr(obj, 'immutable'), 1))

In [6]: obj.immutable
Out[6]: (1,)