Loading topic
functools.partial wraps such a function in a new callable with some arguments already filled in. This chapter covers how partial builds that callab5 min readpartial object is a small callable that remembers a function and some arguments. This chapter shows how to read what it remembers, how a call is assembled from those pieces, and where a partial object differs from an ordinary function.5 min readfunctools.wraps, cache, and lru_cache, which are all decorators or are6 min read@ syntax and know that functions are objects with attributes. The goal is to see exactly what a decorator takes away from the function it wraps. The next chapter fixes that with functools.wraps. First you need to see the damage, becau5 min read@ syntax and that you know a function is an object with attributes such as __name__. The previous chapter showed that a naive decorator replaces a function with its inner wrapper, and that the wrapper's name and docstring replace the 6 min readwrapper(*args, **kwargs) function, and that you have seen @functools.wraps(func) used on that inner function. The previous chapter showed what wraps fixes. This one opens it up. You will see that wraps is a thin layer over `functoo5 min readfunctools.cache and functools.lru_cache before you use them. You will see the problem caching solves, write a small cache by hand, and learn which functions are safe to cache. The next chapter introduces functools.cache itself.7 min readfunctools.cache, the decorator that stores a function's results so repeated calls with the same arguments skip the work. It assumes you can write and call Python functions with keyword arguments, that you know the @decorator syntax, and that you know which built-in types are 5 min read@ decorator syntax, and that you know which built-in types are hashable (a tuple is, a list is not). It also assumes you have seen functools.cache in the previous chapter. Here you will learn what lru_cache adds: a7 min readfunctools attaches to every cached function: cache_info(), which reports how the cache is performing, and cache_clear(), which empties it.6 min read@, know that cache and lru_cache memoize results by argument, and know which built-in types are hashable (tuple, str, int) and which are not (list, dict, set). Caching is easy to add and hard to notice when it is wrong. A cached fu5 min readpartial, wraps, and cache in one program. It assumes you have read the earlier chapters on each tool. You should also be comfortable with decorators that take *args, **kwargs, and with the rule that cache arguments must be hashable. The new material is about interaction5 min read