current position:Home>[Python] function decorators and common decorators
[Python] function decorators and common decorators
2022-02-01 11:24:51 【Hazelnut】
「 This is my participation 11 The fourth of the yuegengwen challenge 6 God , Check out the activity details :2021 One last more challenge 」
Function decorator
Function decorator is used in source code “ Mark ” function , Enhance the behavior of functions in some way .
Decorators are callable objects , Its argument is another function ( Decorated function ). Decorators may handle decorated functions , And then I'm going to return it , Or replace it with another function or callable object .
Take a chestnut :
@decorate
def target():
print('running target()')
# amount to
def target():
print('running target()')
target = decorate(target)
Copy code
One of the major characteristics of decorators is , Can replace the decorated function with other functions . The second characteristic is , They run immediately after the decorated function definition ; This is usually done when importing ( namely Python When loading modules ).
Decorators are usually defined in a module , And then apply it to functions in other modules .
Most decorators define a function inside , Then return it to .
Decorators in standard library
Python There are three built-in functions for decorating methods :property
、classmethod
and staticmethod
.
Another common ornament is functools.wraps
, Its role is to help build a well behaved decorator . The two most noteworthy decorators in the standard library are lru_cache
and singledispatch
(Python 3.4 newly added ). These two ornaments are functools
Defined in module .
functools.lru_cache
functools.lru_cache
Realized the memo (memoization) function . It saves the results of time-consuming functions , Avoid double calculation when the same parameter is passed in .LRU The three letters are “Least Recently Used” Abbreviation , Indicates that the cache will not grow unlimited , Cache entries that are not used for a period of time are thrown away .
lru_cache
Two optional parameters can be used to configure . Its signature is :
functools.lru_cache(maxsize=128, typed=False)
Copy code
maxsize
Parameter specifies how many call results are stored . When the cache is full , The old results will be thrown away , Make room . For the best performance ,maxsize
It should be set to 2 The power of . typed
If the parameter is set to True
, Save the results of different parameter types separately , That is, the floating-point number and integer parameter which are usually considered equal ( Such as 1
and 1.0
) Differentiate .
because lru_cache
Use a dictionary to store results , And the key is created according to the location parameters and keyword parameters passed in during the call , So be lru_cache
Functions of decoration , All its parameters must be hashable .
functools.singledispatch
because Python Overloaded methods or functions are not supported , Therefore, we cannot use different signatures to define variants of functions with the same function name , You can't handle different data types in different ways . stay Python in , A common practice is to use a string of if/elif/elif
, Call special functions , Such as functionA_str
、functionA_int
, wait . This is not convenient for the user to expand the module , And clumsy : A long time , Dispatch function functionA
It's going to get big , Moreover, it is closely coupled with various special functions .
functools.singledispatch
The decorator can split the overall scheme into multiple modules , You can even provide special functions for classes that you can't modify . Use @singledispatch
The ordinary function of decoration will become the universal function (generic function): According to the type of the first parameter , A set of functions that perform the same operation in different ways .
Special functions can be registered anywhere in the system and in any module .
Take a chestnut :
from functools import singledispatch
import numbers
import html
@singledispatch # Tag handling object Base functions of types
def htmlize(obj):
content = html.escape(repr(obj))
return '<pre>{}</pre>'.format(content)
@htmlize.register(str) # Each specialized function is used @«base_function».register(«type») decorate .
def _(text): # The name of the specialized function does not matter ;_ It's a good choice
content = html.escape(text).replace('\n', '<br>\n')
return '<p>{0}</p>'.format(content)
@htmlize.register(numbers.Integral)
def _(n):
return '<pre>{0} (0x{0:x})</pre>'.format(n)
Copy code
Parametric decorators
Let the decorator accept other parameters : Create a decorator factory function , Pass the parameters to it , Returns a decorator , Then apply it to the function to decorate .
Take a chestnut :
registry = set()
def register(active=True): # Accept an optional keyword parameter
def decorate(func): # The real decorator
print('running register(active=%s)->decorate(%s)' % (active, func))
if active: # Only active The value of the parameter ( Get... From a closure ) yes True Register only when func
registry.add(func)
else: # If active Not true , and func stay registry in , Then delete it
registry.discard(func)
return func # decorate It's a decorator , Must return a function
return decorate
@register(active=False) # @register Factory functions must be called as functions , And pass in the required parameters
def f1():
print('running f1()')
@register() # Even if no parameters are passed in ,register Must also be called as a function , That is to return to the real decorator decorate
def f2():
print('running f2()')
Copy code
copyright notice
author[Hazelnut],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011124490665.html
The sidebar is recommended
- Python from 0 to 1 (day 14) - Python conditional judgment 1
- Several very interesting modules in Python
- How IOS developers learn Python Programming 15 - object oriented programming 1
- Daily python, Chapter 20, exception handling
- Understand the basis of Python collaboration in a few minutes
- [centos7] how to install and use Python under Linux
- leetcode 1130. Minimum Cost Tree From Leaf Values(python)
- leetcode 1433. Check If a String Can Break Another String(python)
- Python Matplotlib drawing 3D graphics
- Talk about deep and shallow copying in Python
guess what you like
-
Python crawler series - network requests
-
Python thread 01 understanding thread
-
Analysis of earthquake distribution in the past 10 years with Python~
-
You need to master these before learning Python crawlers
-
After the old friend (R & D post) was laid off, I wanted to join the snack bar. I collected some data in Python. It's more or less a intention
-
Python uses redis
-
Python crawler - ETF fund acquisition
-
Detailed tutorial on Python operation Tencent object storage (COS)
-
[Python] comparison of list, tuple, array and bidirectional queue methods
-
Go Python 3 usage and pit Prevention Guide
Random recommended
- Python logging log error and exception exception callback method
- Learn Python quickly and take a shortcut~
- Python from 0 to 1 (day 15) - Python conditional judgment 2
- Python crawler actual combat, requests module, python to capture headlines and take beautiful pictures
- The whole activity collected 8 proxy IP sites to pave the way for the python proxy pool, and the 15th of 120 crawlers
- Why can't list be used as dictionary key value in Python
- Python from 0 to 1 (day 16) - Python conditional judgment 3
- What is the python programming language?
- Python crawler reverse webpack, a real estate management platform login password parameter encryption logic
- Python crawler reverse, a college entrance examination volunteer filling platform encrypts the parameter signsafe and decrypts the returned results
- Python simulated Login, selenium module, python identification graphic verification code to realize automatic login
- Python -- datetime (timedelta class)
- Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills
- [Python] comparison of dictionary dict, defaultdict and orderdict
- Test driven development using Django
- Face recognition practice: face recognition using Python opencv and deep learning
- leetcode 1610. Maximum Number of Visible Points(python)
- Python thread 03 thread synchronization
- Introduction and internal principles of Python's widely used concurrent processing Library Futures
- Python - progress bar artifact tqdm usage
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
- leetcode 1606. Find Servers That Handled Most Number of Requests(python)
- leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
- 06python learning notes - reading external text data
- [Python] functions, higher-order functions, anonymous functions and function attributes
- Python Networkx practice social network visualization
- Data analysis starts from scratch, and pandas reads and writes CSV data
- Python review (format string)
- [pandas learning notes 01] powerful tool set for analyzing structured data
- leetcode 147. Insertion Sort List(python)
- apache2. 4 + windows deployment Django (multi site)