This article mainly introduces the Pythonfunctools module and explains functools. partial, functool. update_wrapper, functool. wraps, functools. reduce, functools. cmp_to_key, functools. document address of total_ordering and other methods
Functools. partial
Purpose:
Functools. partial allows us to "redefine" the function signature by means of packaging.
Wrap a Callable object with some default parameters. the returned results are callable objects and can be treated like the original object.
Freeze some function location function or keyword parameters, simplify the function, and call more flexible function parameters.
The code is as follows:
# Parameters when args/keywords call partial
Def partial (func, * args, ** keywords ):
Def newfunc (* fargs, ** fkeywords ):
Newkeywords = keywords. copy ()
Newkeywords. update (fkeywords)
Return func (* (args + fargs), ** newkeywords) # Merge and call the original function. the partial parameter is used.
Newfunc. func = func
Newfunc. args = args
Newfunc. keywords = keywords
Return newfunc
Statement:
The code is as follows:
Urlunquote = functools. partial (urlunquote, encoding = 'latin1 ')
When urlunquote (args, * kargs) is called)
Equivalent to urlunquote (args, * kargs, encoding = 'latin1 ')
E. g:
The code is as follows:
Import functools
Def add (a, B ):
Return a + B
Add (4, 2)
6
Plus3 = functools. partial (add, 3)
Plus5 = functools. partial (add, 5)
Plus3 (4)
7
Plus3 (7)
10
Plus5 (10)
15
Application:
Typically, when a function is executed, all necessary parameters must be included for calling.
Then, sometimes the parameters can be known in advance before the function is called.
In this case, one or more parameters of a function can be used in advance, so that the function can be called with fewer parameters.
Functool. update_wrapper
The default partial object does not have _ name _ and _ doc __. in this case, it is difficult to debug the decorator function. use update_wrapper () to copy or add existing partial objects from the original object
It can copy the _ name _, module, _ doc _, and _ dict _ of the encapsulated functions to the encapsulated functions (module-level constants WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES)
The code is as follows:
>>> Functools. WRAPPER_ASSIGNMENTS
('_ Module _', '_ name _', '_ doc __')
>>> Functools. WRAPPER_UPDATES
('_ Dict __',)
This function is mainly used in the decorator function. the decorator returns the function reflection to get the function definition of the function packaging function rather than the original function definition.
The code is as follows:
#! /Usr/bin/env python
# Encoding: UTF-8
Def wrap (func ):
Def call_it (* args, ** kwargs ):
"Wrap func: call_it """
Print 'Before call'
Return func (* args, ** kwargs)
Return call_it
@ Wrap
Def hello ():
"Say hello """
Print 'Hello world'
From functools import update_wrapper
Def wrap2 (func ):
Def call_it (* args, ** kwargs ):
"Wrap func: call_it2 """
Print 'Before call'
Return func (* args, ** kwargs)
Return update_wrapper (call_it, func)
@ Wrap2
Def hello2 ():
"Test hello """
Print 'Hello world2'
If _ name _ = '_ main __':
Hello ()
Print hello. _ name __
Print hello. _ doc __
Print
Hello2 ()
Print hello2. _ name __
Print hello2. _ doc __
Expected result:
The code is as follows:
Before call
Hello world
Call_it
Wrap func: call_it
Before call
Hello world2
Hello2
Test hello
Functool. wraps
Abbreviation of calling function decorator partial (update_wrapper, wrapped = wrapped, assigned = assigned, updated = updated)
The code is as follows:
From functools import wraps
Def wrap3 (func ):
@ Wraps (func)
Def call_it (* args, ** kwargs ):
"Wrap func: call_it2 """
Print 'Before call'
Return func (* args, ** kwargs)
Return call_it
@ Wrap3
Def hello3 ():
"Test hello 3 """
Print 'Hello world3'
Result
The code is as follows:
Before call
Hello world3
Hello3
Test hello 3
Functools. reduce
The code is as follows:
Functools. reduce (function, iterable [, initializer])
Equivalent to the built-in function reduce ()
The reason for this is to make the code more compatible (python3)
Functools. cmp_to_key
Functools. cmp_to_key (func)
Convert the old-fashioned nose-tip function to the key function and use it in methods that accept the key function (such as sorted (), min (), max (), heapq. nlargest (), heapq. nsmallest (), itertools. groupby ())
A comparison function receives two parameters. if the value is less than, a negative number is returned. if the value is equal to or greater than 0, an integer is returned.
The key function receives a parameter and returns a position indicating the parameter in the expected sequence.
For example:
The code is as follows:
Sorted (iterable, key = cmp_to_key (locale. strcoll) # locale-aware sort order
Functools. total_ordering
The code is as follows:
Functools. total_ordering (cls)
This modifier is added when python2.7. it is used to define at least one of the methods of _ lt _, le, gt, and _ ge _ for a class, when this modifier is used, several other comparison functions are automatically implemented in this class.
The code is as follows:
@ 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 ()))
Print dir (Student)
Get
The code is as follows:
['_ Doc _', '_ eq _', '_ ge _', '_ gt __', '_ le _', '_ lt _', '_ module _']