When I was looking through some Kivy code, I came through an example where Python partials were used. Although I've read about partials in the docs, I've never used them in my code. The official docs say:
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords.
Another explanation worded partial as doing roughly this:
def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper
This means that be calling partial(sum2, 4) you create a new function that behaves like sum2, but has one less positional argument. That missing argument is always substituted by 4. After understanding that, the original example given in the Python docs seemed to make more sense.
>>> from functools import partial >>> basetwo = partial(int, base=2) >>> basetwo("111") 7
The original operation for int would be used to type-cast some string. By default, the base is 10 - but that's a parameter that can be changed. We have our partial object basetwo, which from now on simply constructs an integer using the base that was chosen in the object assignment.