Functions
Partial Functions
Without partial, callers repeat the same fixed argument every time they want the specialized behavior.
Source
def apply_tax(rate, amount):
return round(amount * (1 + rate), 2)
print(apply_tax(0.2, 50))Output
60.0partial stores that fixed argument and returns a callable shaped for the remaining arguments.
Source
from functools import partial
vat = partial(apply_tax, 0.2)
service_tax = partial(apply_tax, rate=0.1)
print(vat(50))
print(service_tax(amount=80))Output
60.0
88.0Partial objects expose the function and stored arguments, which is helpful when debugging callback wiring.
Source
print(vat.func.__name__)
print(vat.args)Output
apply_tax
(0.2,)Notes
partialadapts a callable by pre-filling arguments.- The resulting object can be passed anywhere a callable with the remaining parameters is expected.
- Use a regular function when the adapter needs more logic than argument binding.
See also
- related: Functions
- related: Args and Kwargs
- next depth: Callable Objects
Run the complete example
Expected output
60.0
60.0
88.0
apply_tax
(0.2,)
Execution time appears here after you run the example.