Function of the functools module for instance parsing

Source: Internet
Author: User
This article mainly introduces the common function parsing of the functools module in Python, and explains functools respectively. cmp_to_key, functools. total_ordering, functools. reduce, functools. partial, functools. update_wrapper and functools. for more information about how to use wraps, see the next article. This article mainly introduces common function parsing for the functools module in Python and explains functools. cmp_to_key, functools. total_ordering, functools. reduce, functools. partial, functools. update_wrapper and functools. for more information about how to use wraps, see

The functools module provided by Python provides some common high-level functions, that is, special functions used to process other functions. In other words, this module can be used to process callable objects.

Functools module function overview

  • 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 ()

Syntax:

functools.cmp_to_key(func)

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

Old-style comparison function: Receives Two parameters and returns the comparison result. If the return value is smaller than zero, the former is smaller than the latter. if the return value is greater than zero, the opposite is true. if the return value is equal to zero, the two are equal.

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

In Python 3, there are many places where old comparison functions are no longer supported. in this case, you can use cmp_to_key () for conversion.

Example:

sorted(iterable, key=cmp_to_key(cmp_func))

Functools. total_ordering ()

Syntax:

functools.total_ordering(cls)

This is a class decorator used to automatically implement class comparison operations.

We only need to implement the eq () method in the class and any of the following methods lt (), le (), gt (), ge (), then total_ordering () this will automatically help us implement the remaining comparison operations.

Example:

@total_orderingclass 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 ()

Syntax:

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

This function is the same as the built-in reduce () function in Python and is mainly used to compile code compatible with Python 3.

Functools. partial ()

Syntax:

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

This function returns a partial object. calling this object is equivalent to calling the func function, and passing in the location parameter args and keyword parameter keywords. If location parameters are input when this object is called, these parameters are added to args. If a keyword parameter is input, 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 mainly used to "freeze" some parameters of a function. It returns a function object with fewer parameters and simpler use.

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 ()

Syntax:

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

This function is used to update the wrapper function to make it look like the original function. The optional parameter is a tuples. assigned tuples specify the attributes to be replaced directly with the value of the original function. updated tuples specify the attributes to be updated against the original function. The default values of these two parameters are the module-level constants WRAPPER_ASSIGNMENTS and WRAPPER_UPDATES. The former specifies direct value assignment for the name, module, and doc attributes of the function, while the latter specifies to update the dict attributes of the function.

This function is mainly used in the definition of the decorator function and placed before the function is packaged. If the encapsulated function is not updated, the meta information of the decorated function becomes the meta information of the encapsulated function, rather than the meta information of the original function.

Functools. wraps ()

Syntax:

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

Wraps () simplifies the call of 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 be changed to wrapper, and the original function example () Description Document (docstring) will be lost.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.