Partial Application With partial
Concepts covered: Unpacking
functools.partial(func, *args, **kwargs) returns a new callable that remembers some of func's arguments. When you call it, it runs func with the remembered arguments plus the ones you pass now. Fixed positional arguments go in front of the caller's positional arguments, and fixed keywords are merged with the caller's keywords.
from functools import partial
def build_path(env, table, date):
return f"{env}/{table}/{date}"
prod_path = partial(build_path, "prod")
print(prod_path("orders", "2024-05-01"))
parse_hex = partial(int, base=16)
print(parse_hex("ff"), parse_hex("1a"))Output:
prod/orders/2024-05-01 255 26
prod_path needs only table and date, because env is already filled with "prod". parse_hex presets base by keyword, and that works on built-ins like int as well as on functions you write.
Which parameter a preset fills
A fixed positional argument always lands in the leftmost parameter. That works when the value you want to preset comes first in the signature, and silently goes wrong when it comes later. To preset a later parameter, fix it by name.
from functools import partial
def above(value, threshold):
return value > threshold
wrong = partial(above, 1000)
right = partial(above, threshold=1000)
sizes = [250, 4000, 1200]
print(list(filter(wrong, sizes)))
print(list(filter(right, sizes)))Output:
[250] [4000, 1200]
wrong(x) runs above(1000, x), which asks whether 1000 is larger than x, so the filter keeps the small file and drops the 2 large ones. No error is raised, and the result is reversed. right fills threshold and leaves value open for filter to supply.
Overriding and colliding arguments
A keyword fixed by partial behaves like a default: the caller can pass the same keyword again and the caller's value wins. A partial object also exposes its parts as .func, .args and .keywords, which helps when a log line should say what a preset function will do.
from functools import partial
def scale(value, factor, offset=0):
return value * factor + offset
to_ms = partial(scale, factor=1000)
print(to_ms(2.5))
print(to_ms(3, offset=7))
print(to_ms(3, factor=60))
print(to_ms.func.__name__, to_ms.args, to_ms.keywords)Output:
2500.0
3007
180
scale () {'factor': 1000}The third call replaces factor with 60, giving 3 * 60 + 0, and the stored .keywords stay untouched. Positional values cannot be overridden this way. If the caller's positional arguments reach a parameter that is already fixed by keyword, Python raises TypeError and names the parameter that received 2 values.
What happens when this runs?
from functools import partial
def tag(prefix, name, suffix):
return prefix + name + suffix
raw = partial(tag, "dw_", suffix="_raw")
print(raw("orders"))
print(raw("orders", "_v2"))- It prints dw_orders_raw, then dw_orders_v2, because the newer suffix wins
- It prints dw_orders_raw twice, because the preset suffix ignores extras
- It raises TypeError on the first call, since tag needs 3 positional values
- It prints dw_orders_raw, then raises TypeError: multiple values for suffix
Partial or a small def?
- partial(build_path, "prod")
- A single line, with no new def to read
- Links back to the original through .func
- Presets arguments and adds no logic
- def prod_path(table, date)
- Can add checks, formatting or logging around the call
- Has its own name and docstring
- Takes 2 or more lines for what may be a pure preset
Use partial when you hand a function to map, filter or sorted(key=...) and it needs an extra argument those tools never pass. map calls its function with 1 argument per item, so presetting ndigits turns round into a function map can use:
from functools import partial
prices = [3.14159, 2.71828, 9.5]
print(list(map(partial(round, ndigits=2), prices)))Output:
[3.14, 2.72, 9.5]
About this lesson
This section is part of the Functional Programming: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.