I am aware about late bindings in loop in python, but I cant find way to solve this .
def bind_method(object, methods):
for method in methods:
def my_method():
result = method()
return result
setattr(object, method.__name__, my_method)
def test():
class A: pass
def bar():
return "BAR"
def foo():
return "FOO"
a = A()
bind_method(a, [bar, foo])
assert a.foo() == "FOO"
assert a.bar() == "BAR"
if __name__ == "__main__":
test()
I tried with partial in functools but not get success :(
When you call
a.bar()my_methodis invoked and since the for loop has ended the value ofmethodfor it is the last element inmethodslist so you always get"FOO"as result.To check you can add a print statement:
But when I set it directly:
It does work.
Using
functools.partial: