How to Use functools.partial in Python: Simple Guide
Use
functools.partial to fix some arguments of a function and create a new function with fewer parameters. This helps simplify calls by pre-filling common arguments while keeping the original function's behavior.Syntax
The functools.partial function creates a new function by fixing some arguments of an existing function. The syntax is:
functools.partial(func, /, *args, **keywords)
Here, func is the original function, *args are positional arguments to fix, and **keywords are keyword arguments to fix.
python
from functools import partial new_func = partial(func, arg1, arg2, key=value)
Example
This example shows how to use partial to create a new function that always adds 10 to its input.
python
from functools import partial def add(a, b): return a + b add_10 = partial(add, 10) print(add_10(5)) # Adds 10 + 5 print(add_10(20)) # Adds 10 + 20
Output
15
30
Common Pitfalls
One common mistake is misunderstanding the order of fixed arguments. The fixed positional arguments fill the leftmost parameters first. Also, forgetting that partial does not call the function immediately but returns a new callable can confuse beginners.
Another pitfall is using mutable default arguments with partial, which can lead to unexpected behavior.
python
from functools import partial def greet(greeting, name): return f"{greeting}, {name}!" # Wrong: fixing the first argument instead of the second say_hello = partial(greet, "Alice") # This fixes greeting, not name print(say_hello("Hi")) # Output will be 'Alice, Hi!' but greeting is fixed to 'Alice' incorrectly # Right way using keyword argument say_hello_correct = partial(greet, greeting="Hello") print(say_hello_correct("Alice")) # Output: 'Hello, Alice!'
Output
Alice, Hi!
Hello, Alice!
Quick Reference
- Purpose: Fix some arguments of a function to create a simpler new function.
- Import:
from functools import partial - Usage:
new_func = partial(original_func, fixed_args) - Call:
new_func(remaining_args)
Key Takeaways
Use functools.partial to fix some arguments of a function and create a new callable.
Fixed arguments fill the leftmost parameters first unless keywords are used.
Partial functions do not execute immediately; they return a new function.
Avoid mutable default arguments with partial to prevent bugs.
Partial helps simplify repetitive function calls by pre-filling common values.