In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to understand two very practical Python decorators, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
1. Timeout function
The purpose of this function is to add a timeout function to any function that may hang, which is especially useful when writing external API calls, web crawlers, and database queries
The code for the timeout decorator is as follows:
Import signal,functools # two libraries class TimeoutError (Exception) that will be used below: pass # defines an Exception Def timeout (seconds, error_message = 'Function call timed out'): def decorated (func): def _ handle_timeout (signum, frame): raise TimeoutError (error_message) def wrapper (* args, * * kwargs): signal.signal (signal.SIGALRM, _ handle_timeout) signal.alarm (seconds) try: result = func (* args) * * kwargs) finally: signal.alarm (0) return result return functools.wraps (func) (wrapper) return decorated
Use:
@ timeout (5) # defines the following slowfunc function to force TimeoutError Exception to end def slowfunc (sleep_time): import time time.sleep (sleep_time) # if it does not return within 5 seconds. This function is dormant sleep_time seconds slowfunc (3) # sleep 3 seconds, normal return no exception slowfunc (10) # terminated
# # output
TimeoutError Traceback (most recent call last)
2.Trace function
Sometimes for demonstration or debugging purposes, we need to print out the running sequence and calling logic of each step when the program is running. Similar to the bash-x debugging function when writing bash, and then the Python interpreter does not have a built-in function that is useful at this time, so we will "do it ourselves".
The code for the Trace decorator is as follows:
A: there are no answers to problems encountered in study. The editor has created a Python learning exchange group: 725638078 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! Import sys,os,linecachedef trace (f): def globaltrace (frame, why, arg): if why = = "call": return localtrace return None def localtrace (frame, why, arg): if why = = "line": # record the filename and line number of every trace filename = frame.f_code.co_filename lineno = frame.f_lineno bname = os.path.basename (filename) print ("{} ({}): {}" .form at (bname, lineno) Linecache.getline (filename, lineno) .strip ('\ r\ n'),) return localtrace def _ f (* args, * * kwds): sys.settrace (globaltrace) result = f (* args, * * kwds) sys.settrace (None) return result return _ f
Use:
@ tracedef xxx (): print (1) print (22) print (333) xxx () # call
# # output
(3): output of print 1 # @ trace
one
(4): output of print 22 # @ trace
twenty-two
(5): output of print 333 # @ trace
three hundred and thirty three
The above is how to understand two very practical Python decorators. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.