Home > Backend Development > Python Tutorial > How Can I Preset Arguments for a Python Function Using `functools.partial`?

How Can I Preset Arguments for a Python Function Using `functools.partial`?

Patricia Arquette
Release: 2024-12-10 22:21:13
Original
320 people have browsed it

How Can I Preset Arguments for a Python Function Using `functools.partial`?

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
Copy after login

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
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template