Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

functools.partial

Builds a callable with some arguments supplied in advance.

Version: Python 3.14; repository image, production runtime not attested

Syntax

functools.partial(func, /, *args, **keywords)

Builds a callable with some arguments supplied in advance.

A keyword supplied at call time overrides a stored keyword, and new positional arguments fill any Placeholder slots before the rest are appended.

Pre-bind positional arguments and keywords without calling func yet. On invocation, extra positional values follow stored ones, except that 3.14 Placeholder slots must first be filled by positional values. Later keywords override stored keywords. Too few values for the slots raise TypeError. The sample parses '10' first in base 16 then in base 2, giving 16 and 2. CPython 3.14.9 rejects a Placeholder keyword value and a trailing positional Placeholder when constructing the partial, before any later invocation.

from functools import partial, Placeholder as hole
p = partial(str.replace, hole, "a", "x")
assert p("aba") == "xbx"
try:
    p()
except TypeError:
    pass
else:
    raise AssertionError
for make in (lambda: partial(dict, key=hole), lambda: partial(print, hole)):
    try: make()
    except TypeError: pass
    else: raise AssertionError

Examples

import functools
parse = functools.partial(int, base=16)
print(parse("10"), parse("10", base=2))

Result

16 2

Pre-bind positional arguments and keywords without calling func yet. On invocation, extra positional values follow stored ones, except that 3.14 Placeholder slots must first be filled by positional values. Later keywords override stored keywords. Too few values for the slots raise TypeError. The sample parses '10' first in base 16 then in base 2, giving 16 and 2. CPython 3.14.9 rejects a Placeholder keyword value and a trailing positional Placeholder when constructing the partial, before any later invocation.

Sources