Functools
Standard module that provides a number of functions that operate on other functions usually returning new ones, somehow modified.
Very useful module. A sign of a good Pythonista. Most useful functions:
partial
reduce
wraps
total_ordering
lru_cache
functools.partial
New function that calls target function with some arguments already set. This gives a copy of a function with less attributes.
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
What if we want to be able to assign specific positional argument?
It can't be done! Use lambda
instead (of even regular def
)
🪄 Code:
📟 Output:
It is recommended to use lambda
instead of functools.partial
when possible.
functools.reduce
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.
In Python 2
functools.reduce
was builtin functionreduce
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Factorial, "ez mode":
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
functools.lru_cache
Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls.
🪄 Code:
📟 Output:
Last updated