Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Python function decorator

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use the Python function decorator, the article introduces in great detail, has a certain reference value, interested friends must read it!

What is a function decorator

1. The function decorator is a marking function that enhances the function provided by Python.

two。 A decorator is a callable function object whose argument is another function (decorated function)

We can use modifiers to encapsulate a function so that the program runs some code before and after executing the function. This means that the parameter values passed by the caller to the function, the values returned by the function to the caller, and the exceptions thrown by the function can all be accessed and modified by the modifier. This is a useful mechanism to ensure that users use functions in the right way, can also be used to debug programs or implement function registration functions, and there are many other uses.

Second, the execution time of the function decorator

The function decorator is executed directly after being compiled and parsed by the decorated function, and the decorator is executed from top to bottom.

The return function defined inside the function decorator is attached to the execution environment of the decorator.

The function decorator generates a new return function each time it is executed.

Import sysdef dec1 (m): print (f'{sys._getframe (). F_code.co_name} is execute, arg {m. Sys._getframe (). F_code.co_name}') return newm1 @ dec1def M1 (): print (f'{sys._getframe (). F_code.co_name}') @ dec1def M11 (): print (f'{sys._getframe (). F_code.co_name}') if _ _ name__ = ='_ main__': print (M1) print (M11) print (f'm1==m11: {m1==m11}') # dec1 is execute, arg masks dec1 is execute, arg M1 domains m1==m11:False III, variable scope

The combination of variable declaration and assignment operation in Python can easily cause the local variables of the function to cover the variables outside the function.

B=6def f (): print (b) f () # 6b=6def f (): print (b) b = 9f () # UnboundLocalError: local variable'b' referenced before assignment

Through the generated bytecode, we can see the difference in the treatment of variable b between the former directly LOAD_GLOBAL and the latter LOAD_FAST, but assigning a value to b results in an error after print

From dis import disb=6def f (): print (b) # b = 9dis (f) # 50 LOAD_GLOBAL 0 (print) # 2 LOAD_GLOBAL 1 (b) # 4 CALL_FUNCTION 1 # 6 POP_TOP # 8 LOAD_CONST 0 ( None) # 10 RETURN_VALUEfrom dis import disb=6def f (): print (b) b = 9 # 50 LOAD_GLOBAL 0 (print) # 2 LOAD_FAST 0 (b) # 4 CALL_FUNCTION 6 POP_TOP# 6 8 LOAD_CONST 1 (9) # 10 STORE_FAST 0 (b) # 12 LOAD_CONST 0 (None) # 14 RETURN_VALUE

You can use global to force b to be a global variable, and then you can reassign it

B=6def f (): global b print (b) b = 9f () # 6 IV. Closure

Closures are functions that can access non-global variables that are not defined in the body of a function.

Through the _ _ code__ and _ _ closure__ of the function, we can see the local variables, free variables and closures.

Def makesum (): sum = [0] def s (val): sum [0] + = val return sum [0] return ss = makesum () print (s (1)) print (s (2)) print (s.__code__.co_varnames) print (s.__code__.co_freevars) print (s. ) # ('sum',) # (,) # [3]

Based on the scope of Python variables in the three, the above sum can only use list objects, and the nonlocal keyword provided by python can directly use variables of type int.

Def makesum (): sum = 0 def s (val): nonlocal sum sum + = val return sum return ss = makesum () print (s (1)) print (s (2)) print (s.__code__.co_varnames) print (s.__code__.co_freevars) print (s. ) # (,) # 3 5. Retain the metadata of the function

By default, the function decorator replaces the decorated function completely with the returned function, which may lead to problems with serialization or development tool IntelliSense; you can use functools.wraps to retain the standard properties of the original function (name, module, _ _ annotations__, etc.)

Import functoolsdef dec (func): def real ():''this is real function''' pass return realdef wrapsdec (func): @ functools.wraps (func) def real ():' 'this is real function''' pass return real@decdef max (nums):' 'this is max function''' pass@wrapsdecdef sum (nums):' 'this is sum function''' Print (max) print (max.__name__) print (max.__doc__) print (help (max)) print () print (sum) print (sum.__name__) print (sum.__doc__) print (help (sum)) # real# this is real function# Help on function real in module _ main__:# # real () # this is real function# # None# sum# this is sum function# Help on function sum In module _ _ main__:# # sum (nums) # this is sum function# # None

Support keyword parameters and location parameters

Def dec (func): def real (* args, * * kwargs): result = func (* args, * * kwargs) return result return real@decdef sum (* nums, * * kwargs): s = 0 for n in nums: s = s + n for an in kwargs.values (): s = s + a return sprint (sum) 7. Use lru_cache to cache the results

Lru_cache internally uses the parameters of the function as key, and uses dict to cache the execution results to reduce repeated calculations.

By default, 128records are supported to be cached. After that, excess records are discarded by LRU.

You should be careful not to change the parameters during execution, otherwise the validity of the dictionary key will be affected.

From functools import lru_cache@lru_cache () def fibonacci (n): print (f'fibonacci ({n})') if n

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report