New in version 2.5.
The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.
The functools module defines the following function:
func[,*args][, **keywords]) |
def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return func(*(args + fargs), **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc
The partial is used for partial function application which ``freezes'' some portion of a function's arguments and/or keywords resulting in a new object with a simplified signature. For example, partial can be used to create a callable that behaves like the int function where the base argument defaults to two:
>>> basetwo = partial(int, base=2) >>> basetwo.__doc__ = 'Convert base 2 string to an int.' >>> basetwo('10010') 18
wrapper, wrapped[, assigned][, updated]) |
The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the wrapper function is not updated, the metadata of the returned function will reflect the wrapper definition rather than the original function definition, which is typically less than helpful.
wrapped[, assigned][, updated]) |
partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)
as a function decorator when defining a wrapper function. For example:
>>> def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): ... print 'Calling decorated function' ... return f(*args, **kwds) ... return wrapper ... >>> @my_decorator ... def example(): ... """Docstring""" ... print 'Called example function' ... >>> example() Calling decorated function Called example function >>> example.__name__ 'example' >>> example.__doc__ 'Docstring'
'wrapper'
, and the docstring of the
original example() would have been lost.