Python with statement context Manager

Source: Internet
Author: User

Python with statement context Manager

This example describes the Python with statement context manager. We will share this with you for your reference. The details are as follows:

This situation is often encountered in programming: there is a special statement block. Before executing this statement block, you need to execute some preparation actions. After the statement block is executed, you need to continue to perform some final operations. For example, you need to close the file after reading and writing, close the connection after reading and writing the database, lock and unlock the resource, and so on.

In this case, python provides the Context Manager concept. You can use the Context Manager to define/control the preparation action before the code block is executed and the final action after execution.

I. Why use the context manager?

1. No use of the context Manager

Use the try... finally statement to handle exceptions and close the handle.

logger = open("log.txt", "w")try:  logger.write('Hello ')  logger.write('World')finally:  logger.close()print logger.closed

2. Use the context Manager

By default, the built-in file type of Python supports the context management protocol.
Using the context manager with simplifies the process.

with open("log.txt", "w") as logger:  logger.write('Hello ')  logger.write('World')print logger.closed

2. Implement the context manager in two ways.Method 1: implement the _ enter _ and _ exit _ methods of the class. Method 2: contextlib module decorator and generator implementation.

The following two methods are used to implement a custom context manager.

1. Method 1: implement the _ enter _ and _ exit _ methods through classes.

class File(object): def __init__(self, file_name, method):  self.file_obj = open(file_name, method) def __enter__(self):  return self.file_obj def __exit__(self, type, value, traceback):  self.file_obj.close()with File('demo.txt', 'w') as opened_file: opened_file.write('Hola!')

After the _ enter _ and _ exit _ methods are implemented, context management can be performed through the with statement.

A. What happened at the underlying layer?

1. The with statement first saves the _ exit _ method of the File class, and then calls the _ enter _ method of the File class.
2. The _ enter _ method opens the file and returns it to the with statement. The opened file handle is passed to the opened_file parameter.
3. The with statement calls the _ exit _ method temporarily saved, __exit _ method to close the file.

B. Exception Handling

Which steps will the with statement take for exception handling.

1. It passes the type, value, and traceback of the exception to the _ exit _ method.
2. It allows the _ exit _ method to handle exceptions.
3. If _ exit _ returns True, this exception is ignored.
4. If _ exit _ returns anything other than True, this exception will be thrown by the with statement.

Exception thrown

# If an exception is thrown and _ exit _ returns anything other than True, this exception will be thrown by the with statement class File (object): def _ init _ (self, file_name, method): self. file_obj = open (file_name, method) def _ enter _ (self): return self. file_obj def _ exit _ (self, type, value, traceback): self. file_obj.close () print "type:", type print "value:", value print "traceback:", tracebackwith File('demo.txt ', 'w') as opened_file: opened_file.undefined_function ('hola! ') # Output ============================================== ==========## type: <type 'exceptions. attributeError '> # value: 'file' object has no attribute 'undefined _ function' # traceback: <traceback object at 0x000000000262D9C8> # opened_file.undefined_function ('hola! ') # AttributeError: 'file' object has no attribute 'undefined _ function'

Ignore exceptions:

# Ignore exceptions, __exit _ returns True, so this exception is ignored. Class File (object): def _ init _ (self, file_name, method): self. file_obj = open (file_name, method) def _ enter _ (self): return self. file_obj def _ exit _ (self, exception_type, exception_value, traceback): print ("Exception has been handled") self. file_obj.close () return Truewith File('demo.txt ', 'w') as opened_file: opened_file.undefined_function ('hola! ') # Output ======================================## Exception has been handled

2. Method 2: contextlib module decorator and generator implementation

This method is more elegant, and I personally prefer this method.

Yield__enter__Method execution. The code after yield is__exit__Method execution. Basically__enter__And__exit__Method.

# coding:utf-8import contextlib@contextlib.contextmanagerdef myopen(filename, mode): f = open(filename, mode) try:  yield f.readlines() except Exception as e:  print e finally:  f.close()if __name__ == '__main__': with myopen(r'c:\ip2.txt', 'r') as f:  for line in f:   print line

3. associate multiple following statements with each other

You can use multiple context variables directly through a with statement without nesting the with statement.

class File(object): def __init__(self, file_name, method):  self.file_obj = open(file_name, method) def __enter__(self):  return self.file_obj def __exit__(self, exception_type, exception_value, traceback):  self.file_obj.close()  return Truewith File('demo.txt', 'w') as f1,File('demo.txt','w') as f2: print f1,f2# Output============================# <open file 'demo.txt', mode 'w' at 0x000000000263D150> <open file 'demo.txt', mode 'w' at 0x000000000263D1E0>

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.