Introduction to python with statement

Posted by redsox8185 on Mon, 06 Apr 2020 07:50:00 +0200

Read and write resources in python, and finally release resources. You can use try Finally, the structure realizes the correct release of resources. python provides a with statement to make it easier to release resources.

1. python, such as file operation open, can use with statement directly
2. You can customize a support with statement object
3. You can also use with statement object with contextlib
4. Use of with for the object requiring close operation

There are four ways to use annotations in the sample code
# Customizing objects that support with statements
class DummyRes:

    def __init__(self, tag):
        self.tag = tag

    def __enter__(self):
        print("Enter >>> {}".format(self.tag))
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        print("Exit <<< {}".format(self.tag))
        if exc_tb is None:
            print("Exit without Exception {}".format(self.tag))
            return False
        else:
            print("Exit with Exception {}".format(self.tag))
            return True

# Support closing context with statement object
class Closing:

    def __init__(self, thing):
        self.thing = thing

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.thing.close()

class ClosingDemo:

    def __init__(self):
        self.acquire()

    def acquire(self):
        print("Acquire RES")

    def close(self):
        print("Close RES")

from contextlib import contextmanager

class ContextDemo:

    def __init__(self):
        print("Context Demo init")
        raise Exception
        print("Context Demo init")

    def print(self):
        print("Context Demo print 1")
        #raise Exception
        print("Context Demo print 2")

    def close(self):
        print("Context Demo close")

def context_demo():
    print("context demo in")
    raise Exception
    print("context demo out")

@contextmanager
def demo():
    print("Allocate Resoures")
    try:
        yield context_demo
    finally:
        print("raise exception")
    #yield "*** contextmanager demo ***"
    print("Free Resoures")

if __name__ == "__main__":

    # 1. Use with statement (automatically close the file)
    with open("test.txt", "w") as f:
        f.write("write test")

    # 2. Define with statement automatically
    with DummyRes("test") as res:
        print("With body 1")
        raise Exception
        print("With body 2")

    # 3. Define with statement with contextlib
    with demo():
        print("exc demo")

    # 4. closing context (suitable for the case of close operation)
    with Closing(ClosingDemo()):
        print("Use Resoures")

Topics: Python