How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s boost::bind
.
For example:
def add(x, y): return x + y add_5 = magic_function(add, 5) assert add_5(3) == 8
In Tkinter, bind is defined as a Tkinter function for binding events which may occur by initiating the code written in the program and to handle such events occurring in the program are handled by the binding function where Python provides a binding function known as bind() where it can bind any Python methods and ...
The terms parameter and argument can be used for the same thing: information that are passed into a function. From a function's perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that are sent to the function when it is called.
Variadic parameters (Variable Length argument) are Python's solution to that problem. A Variadic Parameter accepts arbitrary arguments and collects them into a data structure without raising an error for unmatched parameters numbers.
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)
I'm not overly familiar with boost::bind, but the partial
function from functools
may be a good start:
>>> from functools import partial >>> def f(a, b): ... return a+b >>> p = partial(f, 1, 2) >>> p() 3 >>> p2 = partial(f, 1) >>> p2(7) 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With