[ Web Proxy ]
URL:
Viewing: https://www.pythonbyexample.dev/examples/partial-functions [Back]  [Original]

Partial Functions Python By Example Skip to main content Python By ExampleJourneysAbout
All examplesPython docs reference

Functions

Partial Functions

functools.partial pre-fills arguments to make a more specific callable.

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.0
f(a, b, c)partial(f, 1)g(b, c)functools.partial(f, 1) pre-fills a=1, returning a thinner callable g(b, c) that only needs the rest.

partial 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.0

Partial 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

See also

ClosuresGlobal and Nonlocal

Run the complete example

code:

Expected output

60.0
60.0
88.0
apply_tax
(0.2,)

Execution time appears here after you run the example.

adewale/pythonbyexample Python 3.13 docs Privacy
Web Proxy Viewer  |  New URL  |  Original Page