Twenty-two, with the 'context manager'

System resources such as files, database connections, socket and so on, open the application after completing these resources and execute business logic, it must be closed (off) the resources, otherwise the situation will be occupied resources.

Ordinary version of the open file:

f = open("output.txt", "w")
f.write ( " Python Zen " )
f.close()

Use the way try except to open the file:

 f = open("output.txt", "w")
    try:
        f.write("python之禅")
    except IOError:
        print("oops error")
    finally:
        f.close()

With the use of open document:

with open("output.txt", "r") as f:
        f.write ( " Python Zen " )

  The return value is assigned to variable open method F, when the code block away with, the system automatically calls f.close () method, with the use of effects and try / finally statement is the same.

 

Context Manager

  Any implements The __enter __ () and The __exit __ () method can be called the context object manager.

class File():

    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        print("entering")
        self.f = open(self.filename, self.mode)
        return self.f

    def __exit__(self, *args):
        print("will exit")
        self.f.close()

  __enter __ () method returns an object resource, here's what you will want to open the file object, __ exit __ () method to deal with some cleanup work. Because the File class implements the context manager, you can now use with a statement.

with File('out.txt', 'w') as f:
    print("writing")
    f.write('hello, python')

  This eliminates the need to call the close method to display, to call automatically by the system, even if the middle of an exception is encountered close method will be invoked.

Another way to achieve a context manager

  Contextmanager Python also provides a decorator, further simplifying the implementation of the context manager. The yield function by divided into two parts, in the statement is executed before __enter__ yield method, the statement after the execution __exit__ process yield. Immediately after the yield value is the return value of the function

from contextlib import contextmanager

@contextmanager
def my_open(path, mode):
    f = open(path, mode)
    yield f
    f.close()

  transfer

with my_open('out.txt', 'w') as f:
    f.write("hello , the simplest context manager")

 

Guess you like

Origin www.cnblogs.com/nuochengze/p/12666088.html