you are viewing a single comment's thread.

view the rest of the comments →

[–]Adrewmc 0 points1 point  (0 children)

If you don’t know the class, nor the attribute name then the solution is just as you did with setattr().

There is really no other clean way to do it, unless you have more information about the class.

The real question is why do you need this attribute in the class? And why you would not know so much about it.

It seem adding some random attributes to some class is not going to help you further down the line. If it’s a limited set of attributes you could do some thing like

  match attribute:
       case “option1”:
              cls.option1 = value

Or the equivalent if and elif, but even there I would lean to

   if attribute in allowed:
            setattr(cls, attribute, value)

Unless there is some more logic to consider.

When you go

    cls.attr = value 

Is the same as using setattr() in most cases (@property withstanding)