Python Learning Notes-context

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.