Python context management - usage of the with statement

Please indicate the source for reprinting: http://blog.csdn.net/jinixin/article/details/72590815

When I read the part about the with statement in Python core programming, I didn't understand what it was talking about? What benefits can the with statement bring? Later, my understanding of it became clearer, so I want to talk about my current understanding of the with statement in this article, and this article will be updated again later.
I first introduce the concept of with, then talk about two methods related to it, and finally throw an example. You can look back at these concepts with examples, hoping to help everyone.


The usefulness of with


I understand the with statement as a kind of encapsulation of try, except and finally . Using the with statement can make the program structure seem simpler, avoid code duplication, and be more pythonic. The with statement can only work on objects that support the context management protocol, that is, the object must implement the __enter__ and __exit__ methods.


the appearance of with

with expression [as variable]:
    with clause block

Specific examples, such as opening a file and printing:

with open('/path/to/file','r') as file:
    for line in file:
        print line,

The above code can automatically close the file when it is executed, regardless of whether there is an exception; even by modifying it, we can let with handle the exception automatically. In short, with allows us to shift our attention from worrying about releasing resources, handling exceptions and other trivial matters to how to write better code and make programs more efficient.



with statement execution flow


This part can be viewed in conjunction with the above with statement structure.

First, with evaluates the following expression, which returns an object that must contain two special methods, __enter__ and __exit__. Once the object is returned, the __enter__ method will be called automatically, and the result returned by this method will be assigned to the variable after the as keyword. Note here that the result of the expression after with is not assigned to the variable, but the return value of the __enter__ method is assigned to the variable.

The role of the with statement expression is to return an object that follows the context management protocol, that is, the object must implement the __enter__ and __exit__ methods.


Two necessary methods to implement the context management protocol


__enter__:

1) Form: __enter__(self)
2) This method is mainly responsible for some configuration before the execution of the with clause block.
3) When the expression returns the result object, the method of the returned object is called immediately. If there is the as keyword after the expression, the return value of the method is assigned to the variable after as; if there is no as keyword, the return value of the method is discarded.

__exit__:

1) Form: __exit__(self, exc_type, exc_instance, traceback), the three parameters represent exception type, exception instance, and traceback function respectively. If no exception occurs in the with clause, all three parameters are None; but once an exception occurs, the three parameters will be filled.
2) This method is executed after the entire with statement block is completed, and is used to release resources or handle exceptions. This method will always execute even if an exception occurs within the with clause block.
3) When an exception occurs in the with sub-statement block, the __exit__ method will be executed immediately, and the __exit__ method can choose whether to handle and "cover" the exception. When the __exit__ method returns True, the Python interpreter will continue to execute the code after the with statement (note that the code after the with clause block will not be executed), and when it returns False, this exception will be thrown.


example


Finally, a useful example is about the database (MySQLdb is a third-party module, which can be installed by "pip install mysql-python"):
#!/usr/bin/env python
# coding=utf-8

import MySQLdb


class SqlTool(object):

    def __init__(self, db, user='database user', pwd='database password', host='localhost', port=3306):
        self.connect = MySQLdb.connect(user=user, passwd=pwd, host=host, port=port, db=db) # Create database connection
        self.cursor = self.connect.cursor() # create a cursor

    def __enter__(self):
        return self.cursor # Return the cursor to the cursor variable of the with statement

    def __exit__(self, exc_type, exc_instance, traceback):
        if exc_instance:
            print exc_instance
        self.cursor.close() # close the cursor
        self.connect.commit() # Confirm commit
        self.connect.close() # close the connection
        return True # all exceptions that occur in the with statement are not thrown

with SqlTool(db='test') as cursor:
    cursor.execute('insert into people(name, age) values (%s, %s)', ('jinixin', 20))


Refer to Section 10.4 of Python Core Programming Second Edition, Chapter 2 of Advanced Python Programming. If there is any inappropriate place in the

text , please include and point out, thank you

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325441386&siteId=291194637