Table of Contents
partial
update_wrapper
wraps
reduce
cmp_to_key
lru_cache
singledispatch
Home Backend Development Python Tutorial Summary of using Python's functools module

Summary of using Python's functools module

Jul 27, 2022 pm 05:27 PM
python

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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']
Copy after login

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()   # 清空缓存
Copy after login

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>
Copy after login

【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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles