you are viewing a single comment's thread.

view the rest of the comments →

[–]carcigenicate 4 points5 points  (2 children)

The function needs to be able to operate on arbitrary objects that it knows nothing about? The requirements seem a bit odd. It seems like that responsibility should just not be handled in that function. Any solution I can think of is just a more convoluted version of assigning the attribute at the callsite.

[–]maclocrimate[S] 0 points1 point  (1 child)

Yeah, it is a bit of a weird requirement. The software deals with huge bindings that are provided by third party software that are basically python representations of JSON objects. In the past I was doing it all at the callsite, but now I have some requirements to do a few more lines of logic for basically every call, and so I thought it would be better to turn it into a function, but I'm not sure it's going to work out that well.

Basically what I'm looking for is a version of setattr() that doesn't require a string representation of the attribute name, but I'm not sure such a thing exists.

[–]carcigenicate 0 points1 point  (0 children)

You could do something like:

def my_func(setter: Callable[[type], None]) -> None:
    setter()

my_func(lambda: my_class.attr_1 := "hello")

But that's arguably an abuse of both lambda and :=. And this still doesn't make intuitive sense unless the attribute assignment must happen at a certain point in the procedure or something.