Python has a special module called the context module, which can be combined with a to implement some functions.
His execution is that the user needs a function that defines a generator, and with this function, he executes the code before the yield, then jumps out, executes the code under the With statement, and then switches back to the function, executing the code after finally.
Like what
Import Contextlib@contextlib.contextmanagerdef worker_state (State_list, Worker_thread): State_list.append (Worker_ Thread) Try:yield finally:state_list.remove (worker_thread) print (state_list) free_list = []current_thread = "Alex" with Worker_state (Free_list, Current_thread): print (123) print (456) print (free_list)- ---------123456[' Alex ' []
Example 2 if with followed by an as, we can pass an object to as above the yield, such as below I have a list object to the TT
Import contextlibimport socket@contextlib.contextmanagerdef Test (num): a=[] a.append (num) Try:yield a finally:num+=100 print (num) with Test (a) as Tt:print (TT)------------[20]120
This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1870150
Python Learning Notes-context