Home  >  Article  >  Backend Development  >  Summary of using Python's functools module

Summary of using Python's functools module

WBOY
WBOYforward
2022-07-27 17:27:272771browse

This article brings you relevant knowledge about Python. It mainly introduces the use and description of Python's functools module. It has a good reference value. Let's take a look at it together. I hope it will be helpful to everyone. helpful.

Summary of using Python's functools module

[Related recommendations: Python3 video tutorial]

partial

is used to create a partial function, The default parameters wrap a callable object, and the returned result is also a callable object.

Partial functions can fix some parameters of the original function, making it easier to call.

from functools import partial

int2 = partial(int, base=8)
print(int2('123'))
# 83

update_wrapper

Functions wrapped using partial do not have __name__ and __doc__ attributes.

update_wrapper Function: Copy the __name__ and other attributes of the wrapped function to the new function.

from functools import update_wrapper
def wrap2(func):
    def inner(*args):
        return func(*args)
    return update_wrapper(inner, func)

@wrap2
def demo():
    print('hello world')

print(demo.__name__)
# demo

wraps

The warps function is to copy the __name__ of the decorated function in the decorator.

It is a wrapper on update_wrapper

from functools import wraps
def wrap1(func):
    @wraps(func)    # 去掉就会返回inner
    def inner(*args):
        print(func.__name__)
        return func(*args)
    return inner

@wrap1
def demo():
    print('hello world')

print(demo.__name__)
# demo

reduce

In Python2, it is equivalent to the built-in function reduce

The function of the function is to summarize a sequence For an output

reduce(function, sequence, startValue)

from functools import reduce

l = range(1,50)
print(reduce(lambda x,y:x+y, l))
# 1225

cmp_to_key

There is a key parameter in list.sort and the built-in function sorted

x = ['hello','worl','ni']
x.sort(key=len)
print(x)
# ['ni', 'worl', 'hello']

Before Python3, the cmp parameter was also provided to compare two The element

cmp_to_key function is used to convert the old comparison function into the key function

lru_cache

allows us to quickly cache or uncache the return value of a function.

This decorator is used to cache the call results of functions. For functions that need to be called multiple times, and the parameters are the same for each call, you can use this decorator to cache the call results, thereby speeding up the program.

This decorator will cache different call results in memory, so you need to pay attention to the memory usage issue.

from functools import lru_cache
@lru_cache(maxsize=30)  # maxsize参数告诉lru_cache缓存最近多少个返回值
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)
print([fib(n) for n in range(10)])
fib.cache_clear()   # 清空缓存

singledispatch

Single dispatcher, new in Python3.4, is used to implement generic functions.

Determine which function to call based on the type of a single parameter.

from functools import singledispatch
@singledispatch
def fun(text):
    print(&#39;String:&#39; + text)

@fun.register(int)
def _(text):
    print(text)

@fun.register(list)
def _(text):
    for k, v in enumerate(text):
        print(k, v)

@fun.register(float)
@fun.register(tuple)
def _(text):
    print(&#39;float, tuple&#39;)
fun(&#39;i am is hubo&#39;)
fun(123)
fun([&#39;a&#39;,&#39;b&#39;,&#39;c&#39;])
fun(1.23)
print(fun.registry)    # 所有的泛型函数
print(fun.registry[int])    # 获取int的泛型函数
# String:i am is hubo
# 123
# 0 a
# 1 b
# 2 c
# float, tuple
# {<class &#39;object&#39;>: <function fun at 0x106d10f28>, <class &#39;int&#39;>: <function _ at 0x106f0b9d8>, <class &#39;list&#39;>: <function _ at 0x106f0ba60>, <class &#39;tuple&#39;>: <function _ at 0x106f0bb70>, <class &#39;float&#39;>: <function _ at 0x106f0bb70>}
# <function _ at 0x106f0b9d8>

【Related recommendations: Python3 video tutorial

The above is the detailed content of Summary of using Python's functools module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete