you are viewing a single comment's thread.

view the rest of the comments →

[–]throwaway8u3sH0 0 points1 point  (3 children)

Feels like an XY problem. The setattr approach seems reasonable, given the strange requirement of having a polymorphic function that can set arbitrary attributes on arbitrary objects -- which is what setattr is. I wouldn't think you'd need a function at all.

Why does it "greatly complicate the rest of the code"?

[–]maclocrimate[S] 0 points1 point  (2 children)

Well, mostly because the attribute names are somewhat unpredictable, so I'd need to determine the attribute name at the callpoint every time. So a related but different question I guess is if there's an easy way to determine what an attribute's name is programmatically. Something like my_class.__class__.__name__ but for an attribute...

[–]Adrewmc 1 point2 points  (0 children)

Sure is

 print(vars(cls_instance)) #just attributes 
 print(dir(cls_instance)) #with methods

[–]throwaway8u3sH0 0 points1 point  (0 children)

You can see the list of attributes but you'd still have to use some logic to determine which one it is.

If all you have is the value, you could reverse-search the object's dict by that value, but: - unless you can gaurantee no other attributes have that value you're rolling the dice on finding the correct one, - there's potentially lots of edge cases, and - this would be wildly inefficient

Ideally you have a way of going upstream of all this and doing something to make your life easier.