Function resolution of functools module in Python

  • 2020-05-26 09:38:32
  • OfStack

The functools module, which comes with Python, provides some common higher-order functions, which are special functions for handling other functions. In other words, you can use this module to process callable objects.

Overview of functools module functions

functools.cmp_to_key(func) functools.total_ordering(cls) functools.reduce(function, iterable[, initializer]) functools.partial(func[, args][, *keywords]) functools.update_wrapper(wrapper, wrapped[, assigned][, updated]) functools.wraps(wrapped[, assigned][, updated])

functools.cmp_to_key()

Grammar:

functools.cmp_to_key(func) 

This function is used to convert an old-style comparison function into a keyword function.

The old comparison function: takes two arguments and returns the result of the comparison. If the return value is less than zero, the former is less than the latter; if the return value is greater than zero, the reverse; if the return value is equal to zero, the two are equal.

Keyword function: takes one parameter and returns its corresponding comparable object. For example, sorted(), min(), max(), heapq.nlargest (), heapq.nsmallest (), itertools.groupby () can all be used as keyword functions.

In Python 3, where the old comparison function is no longer supported, you can use cmp_to_key() for conversion.

Example:


sorted(iterable, key=cmp_to_key(cmp_func)) 

functools.total_ordering()

Grammar:

functools.total_ordering(cls) 

This is a class decorator that automatically implements class comparison operations.

We only need to implement the method of s 62en__ () and any one of the following methods with s 62en__ (), s 6en__ (), s 6en__ (), s 6en__ (), s 6en__ (), s 6en__ (), s 6en__ () in the class, then total_ordering() will automatically help us with the rest of the comparison operations.

Example:


@total_ordering
class Student: 
  def __eq__(self, other):
    return ((self.lastname.lower(), self.firstname.lower()) ==
        (other.lastname.lower(), other.firstname.lower()))
  def __lt__(self, other):
    return ((self.lastname.lower(), self.firstname.lower()) <
        (other.lastname.lower(), other.firstname.lower()))

functools.reduce()

Grammar:

functools.reduce(function, iterable[, initializer]) 

This function is the same as Python's built-in reduce() function, and is primarily used to write Python 3-compliant code.

functools.partial()

Grammar:

functools.partial(func[, *args][, **keywords]) 

This function returns an partial object, which has the effect of calling the func function and passing in the location parameter args and the keyword parameter keywords. If location parameters are passed in when the object is called, they are added to args. If a keyword parameter is passed in, it is added to keywords.

The equivalent implementation of the partial() function is roughly as follows:


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() function is primarily used to "freeze" parts of a function, returning a simpler function object with fewer arguments.

Example:


>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18 


functools.update_wrapper()

Grammar:

functools.update_wrapper(wrapper, wrapped[, assigned][, updated])

This function is used to update the wrapper function (wrapper) so that it looks like the original function 1. The optional parameter is a tuple, with the assigned tuple specifying the property to be replaced directly with the value of the original function, and the updated tuple specifying the property to be updated against the original function. The default values for these two parameters are module level constants: WRAPPER_ASSIGNMENTS and WRAPPER_UPDATES, respectively. The former specifies the direct assignment of the properties of the packaging function s s s 134en__, s 135en__, s 136en__, while the latter specifies the renewal of the properties of the packaging function s s s s 137en__.

This function is mainly used in the definition of decorator functions, placed before the wrapper function. If the wrapper function is not updated, the meta-information of the decorated function becomes meta-information of the wrapper function instead of meta-information of the original function.

functools.wraps()

Grammar:

functools.wraps(wrapped[, assigned][, updated])

wraps() simplifies calls to the update_wrapper() function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned, updated=updated).

Example:


>>> from functools import wraps
>>> 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' 

If you do not use this function, the function name in the example will become wrapper, and the documentation for the original function example() (docstring) will be lost.


Related articles: