python context manager (Context managers)

Copyright: arbitrary, seeding https://blog.csdn.net/qq_32662595/article/details/85090821!

Context Manager allows you when there is a need to accurately allocate and release resources.

Demand:
There are two junction related operations need to be performed, then also place a code in the middle thereof.

with open('some_file', 'w') as opened_file:
    opened_file.write('Hola!')

Equivalent to:

file = open('some_file', 'w')
try:
    file.write('Hola!')
finally:
    file.close()

A common use case context manager is locking and unlocking resources, and close open files.

Based on the implementation class

Customize to open the file manager context

A context manager class, at least to define __enter__and __exit__methods.

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()

Using a custom manager with the:

with File(fileName ,method) as opened_file:
    opened_file.write('Hola!')

Procedure :

  1. with the staging of the first sentence __exit__ method of the File class
  2. It then calls the method of the File class __enter__
  3. __enter__ method opens the file and return to the with statement
  4. Open the file handle is passed to parameters opened_file
  5. Use .write () to write files
  6. Before staging method with statement calling __exit__
  7. __exit__ method to close the file

Exception Handling:

  1. It passes unusual type, value and traceback method to __exit__
  2. It makes __exit__ way to handle exceptions
  3. If __exit__ returns True, then the exception is handled gracefully
  4. If __exit__ returned is anything other than True, then this exception will be thrown out with the 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):
        print("Exception has been handled")
        self.file_obj.close()
        return True
        
with File(fileName, 'w') as opened_file:
    opened_file.undefined_function()

Based achieve generator

The decorative device (Decorators) and the generator (Generators) context manager implemented. Python has a contextlibmodule dedicated to this purpose. We can use a generator function to implement a context manager.

from contextlib import contextmanager

@contextmanager
def open_file(name):
    f = open(name, 'w')
    yield f
    f.close()
  1. Python interpreter encounters the yield keyword. For this reason it creates a generator instead of a normal function.
  2. Because this decorator, contextmanager will be called and passed into the function name (open_file) as a parameter.
  3. contextmanager function returns a package had to GeneratorContextManager object generator.
  4. GeneratorContextManager is assigned to open_file function, we are actually calling GeneratorContextManager object.

Guess you like

Origin blog.csdn.net/qq_32662595/article/details/85090821