Python context Manager

Source: Internet
Author: User
Tags object object terminates

My understanding of the concept of the context in which the calculator runs is not very deep; as I understand it, the required resources, running environment, etc. will be serialized before the program is run, and then added to the CPU's task queue, waiting for the dispatch system to allocate time slice execution. Let's talk about the use of the Python context manager.

Custom Context Manager
    • The most common context manager in Python is the opening and closing of files.
withopen(filename,‘r‘asfile:    file.read()

Principle

    • The python context uses the WITH trigger, which implements the __enter__ and __exit__ two magic methods internally.
classContextObject):def __init__( Self):Print(' AAAA ')def __enter__( Self):Print(' bbbb ')def __exit__( Self, Exc_type, Exc_val, EXC_TB):Print(' CCCC ')# Exc_type: type of exception;# Exc_val: Exception details;# EXC_TB: where the exception occurred;# If no exception occurs, the above three values are none withContext () asF:" subject Logic"    Print(' xxxx ')# OutputAaaabbbbxxxxcccc
    • When using the WITH Trigger Manager, first initialize execution __init__ to get an object, then execute the __enter__ method, then execute the principal program logic, and finally execute the __exit__ method.

Attention

    • When the program body logic executes and exits the WITH statement block or the principal logic block, the __exit__ method is automatically executed, and the exception parameters are passed in, and if there is no exception, none is passed.

    • If the principal logic code has an error, but the __exit__ function returns True, the With statement body Logic block exception is not thrown, terminates the program, and if none or false is returned, the exception is actively raise and the program terminates.

Summarize the full principle of the context Manager
    1. Initialize gets a context manager object;

    2. The exit () method of the load context manager is reserved;

    3. Call the context Manager's enter () method, or, if there is an as F clause, assign the return value of the Enter () method to F;

    4. Executing the body logic code block;

    5. Call the exit () method of the context manager;

Python's context management tool Contextlib
    • Python has a more elegant way of managing the context manager.
import contextlib@contextlib.contextmanagerdef test():    print(‘aaaaaa‘)    try:        yield1    finally:        print(‘bbbbb‘)withas f:    print(‘ccccc‘)# 输出aaaaaacccccbbbbb

The underlying simplified version of the principle

classContextTest (Object):def __init__( Self): Self. f=  Self. Test ()def __enter__( Self):return Next( Self. f)def __exit__( Self, Exc_type, Exc_val, EXC_TB):Try:Next( Self. f)except stopiteration:return False    defTest Self):Print(' aaaaaa ')Try:yield 1        finally:Print(' bbbbb ') withContextTest () asF:Print(f)Print(' KKKKKK ')
    • Description
    1. Initializes a ContextTest context Manager object object, resulting in an object's generator test ()

    2. The exit () method of the load context manager is reserved;

    3. Call the context Manager's enter () method, and execute the next () method to wake the test () generator and execute the code in front of the yield keyword;

    4. Executing the principal logic code;

    5. Call the exit () method of the context manager; The method calls the next () method to wake the generator again, executing the code after the yield keyword;

Python context Manager

Related Article

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.