The partial function appeared in Python's standard library (functools module) starting with Python 2.5 to implement the currying pattern and partial application of arguments to a function. partialmethod was introduced in Python 3.4 for similar use in class methods.
In real projects, there often arises a need to fix part of the arguments to a function in order to obtain a new function with "remembered" values of some arguments. This is convenient for callbacks, argument-passing templates, or for improving code readability, especially in functional programming and when using APIs that expect a certain style of functions.
The partial function returns a new function object in which some of the passed arguments or keyword arguments are "hard-coded" (fixed). partialmethod implements the same approach for class methods, correctly supporting the mechanics of self/cls passing.
Example code:
from functools import partial, partialmethod def power(base, exponent): return base ** exponent # Fixing exponent = 2 square = partial(power, exponent=2) print(square(5)) # 25 class Math: def power(self, base, exponent): return base ** exponent square = partialmethod(power, exponent=2) m = Math() print(m.square(5)) # 25
Key features:
Can partial be used for class methods to obtain an analog of partialmethod?
No, partial does not correctly handle self/cls, its use on class methods does not work as expected: self will not be automatically supplied.
class C: def m(self, x, y): return x + y wrong = partial(m, y=2) # Incorrect!
Calling c.wrong(5) will raise TypeError because self will not be passed automatically.
Is the object created with partial a function?
Yes, the result of partial is an object that behaves like a function, supports invocation, name, docstring, etc., but it is not a regular function; it is an object of the partial class that implements the call protocol.
from functools import partial f = partial(pow, 2) print(type(f)) # <class 'functools.partial'>
Does partial work with default arguments of functions?
Yes, partial can "override" default values in the inner function; if arguments are passed to partial, they take precedence over default values in the function itself. However, it is important not to duplicate values, otherwise, an error will occur.
A developer applies partial for a class method instead of partialmethod:
class MyClass: def f(self, x, y): ... squared = partial(f, y=2) ... obj = MyClass() obj.squared(5) # TypeError: missing 1 required positional argument: 'self'
Pros:
Cons:
Instead, partialmethod is applied:
from functools import partialmethod class MyClass: def f(self, x, y): return x + y squared = partialmethod(f, y=2) obj = MyClass() print(obj.squared(5)) # 7
Pros:
Cons: