Create a callable with selected arguments pre-filled.
What You Will Learn
partial(function, *args, **kwargs) returns a callable that supplies stored arguments when invoked. Later keyword arguments can override matching fixed keywords. It does not call the original function immediately.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from functools import partial
def display_price(amount, currency):
return f'{amount} {currency}'
in_dollars = partial(display_price, currency='USD')
print(in_dollars(45))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: functools.
- The function display_price defines reusable behavior; its body executes when it is called, not when it is declared.
- The variable in_dollars holds the result of partial(display_price, currency='USD'). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression in_dollars(45) prints 45 USD. Compare that result with the rule above before you change the argument.
Expected output from the example:
45 USD
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from functools import partial
def tax(price, rate):
return price * rate
vat = partial(tax, rate=0.2)
print(vat(50))
Expected output:
10.0
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Create a fixed-tax-rate calculation using partial().
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Calling the wrapped function while creating a partial instead of passing the function itself.
- Overlooking this documented constraint: it does not call the original function immediately.
Key Takeaways
- Create a callable with selected arguments pre-filled.
- partial(function, *args, **kwargs) returns a callable that supplies stored arguments when invoked.
- Apply this operation only after checking the assumptions and input conditions shown in the example.