Issue
How can I bind arguments to a Python function so that I can call it later without arguments (or with fewer additional arguments)?
For example:
def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
What is the magic_function
I need here?
It often happens with frameworks and libraries that people accidentally call a function immediately when trying to give arguments to a callback: for example on_event(action(foo))
. The solution is to bind foo
as an argument to action
, using one of the techniques described here.
Some specific examples: Why is my Button's command executed immediately when I create the Button, and not when I click it?, thread starts running before calling Thread.start.
Solution
functools.partial
returns a callable wrapping a function with some or all of the arguments frozen.
import sys
import functools
print_hello = functools.partial(sys.stdout.write, "Hello world\n")
print_hello()
Hello world
The above usage is equivalent to the following lambda
.
print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw)
Answered By - Jeremy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.