How to Bind Arguments to a Python Function
In Python, one can encounter situations where binding arguments to a function is necessary for later execution without the need for additional arguments. Consider the example:
def add(x, y): return x + y add_5 = magic_function(add, 5) assert add_5(3) == 8
In this scenario, we need to determine the magic_function that can bind the argument 5 to the add function.
The solution lies in using the functools.partial module:
import functools add_5 = functools.partial(add, 5) # Bind '5' as the first argument to 'add' assert add_5(3) == 8 # Call 'add_5' with '3' as the second argument
functools.partial effectively creates a callable object that wraps the original function with a preset argument. This allows us to execute the function later on without providing the fixed argument explicitly.
The following code demonstrates an equivalent approach using a lambda expression:
print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw)
Here, the arguments to print_hello are treated as if they were given to sys.stdout.write, allowing for flexible argument passing during execution.
The above is the detailed content of How Can I Preset Arguments for a Python Function Using `functools.partial`?. For more information, please follow other related articles on the PHP Chinese website!