The functools
module in the standard library provides several tools for manipulating and extending functions.
The update_wrapper()
function in the module is used to update the properties of a wrapper function so that it is indistinguishable from the wrapped function. The function allows the wrapper to be used similarly to the wrapped function, while preserving metadata associated with the original function, such as its __name__
, __doc__
, __module__
, etc. This ensures that the wrapper function will interact seamlessly with other code expecting the original function.
By default wrapper functions do not inherit properties of the wrapped functions.
As you can see above, the properties being returned are of the wrapper function rather than the original.
How the update_wrapper function works
As mentioned earlier, the update_wrapper()
function makes the wrapper function indistinguishable from the original function. It assigns the necessary properties to the wrapper function, such as __name__
, __doc__
, __module__
, __dict__
, etc.
update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
copy
Examples with functools wrappers
The functools
module provides various wrapper functions which we can use to demonstrate further how the update_wrapper()
function works.
The partial
class in the module is used to create partial functions which creates versions of a function in which some arguments are already pre-filled. We used it above to create a version of the builtin sorted()
function in which elements are sorted by their absolute value by default. We then used the update_wrapper()
function to update the properties of the newly created abs_sorted
function so that it matches those of the original sorted()
function.