Partial Prebinds Arguments For Later Calls
functools.partial binds leading positional and keyword arguments ahead of time, and the resulting object exposes func and keywords for introspection.
Code
from functools import partial
def scale(value, factor, offset=0):
return value * factor + offset
# partial 预绑定一部分参数(prebind),剩下的留给调用时传
to_cents = partial(scale, factor=100)
print(to_cents(12.5), to_cents(0.99))
# 位置参数同样支持:从左往右绑定
double = partial(scale, factor=2)
print(double(21), double(-3, offset=1))
# partial 对象可自省:原函数与绑定值都能读回来
print(double.func.__name__, double.keywords)
# 常见用法:给 map 提供带上下文的单参函数
readings = [1024, 2048, 4096]
print(list(map(double, readings)))Output
Captured from a sandboxed run of this snippet in the build pipeline.
1250.0 99.0
42 -5
scale {'factor': 2}
[2048, 4096, 8192]How it works
Count the function scale as the entire surface area of Partial Prebinds Arguments For Later Calls.
Using it
The main signature reads def scale(value, factor, offset=0)
The surface worth importing is scale; the helpers around it are private to the snippet.
Key statements
def scale(value, factor, offset=0):
return value * factor + offset
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `functools`. The file defines `scale` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.