Python dry goods: The master brother article teaches you how to use python with as! ! !

What is the With statement?

Some tasks may need to be set up in advance and clean up afterwards. For this scenario, Python's with statement provides a very convenient way to handle it. A good example is file processing. You need to obtain a file handle, read data from the file, and then close the file handle.

If the with statement is not used, the code is as follows:

file = open("/tmp/foo.txt")

data = file.read()

file.close()

There are two problems here. One is that you may forget to close the file handle; the other is that the file read data is abnormal and no processing is performed. The following is an enhanced version of handling exceptions:

file = open("/tmp/foo.txt")try:

    data = file.read()finally:

    file.close()

Although this code works well, it is too verbose. This is the time for with to show its skills. In addition to a more elegant syntax, with can also handle exceptions generated by the context. Here is the code for the with version:

with open("/tmp/foo.txt") as file:

    data = file.read()

with如何工作?

This seems full of magic, but not only magic, Python's handling of with is also very clever. The basic idea is that the object evaluated by with must have an __enter__() method and an __exit__() method.

After the statement following with is evaluated, the __enter__() method of the returned object is called, and the return value of this method will be assigned to the variable following as. When all the code blocks behind with are executed, the __exit__() method of the returned object will be called.

The following example can illustrate how with works:

#!/usr/bin/env python

# with_example01.py

 class Sample:

    def __enter__(self):

        print "In __enter__()"

        return "Foo"

    def __exit__(self, type, value, trace):

        print "In __exit__()"

 def get_sample():

    return Sample()

with get_sample() as sample:

    print "sample:", sample

Recommendation: 020 is continuously updated, the small circle of boutiques has new content every day, and the concentration of dry goods is extremely high.
There are everything you want to make connections and discuss technology!
Be the first to join the group and outperform your peers! (There is no fee for joining the group)
Click here to communicate and learn with Python developers.
Group number: 745895701
application and delivery :
Python software installation package, Python actual combat tutorial,
free collection of materials, including Python basic learning, advanced learning, crawling, artificial intelligence, automated operation and maintenance, automated testing, etc.

Run the code, the output is as follows

In __enter__()

sample: Foo

In __exit__()

As you can see,

1. The __enter__() method is executed

2. The value returned by the __enter__() method-"Foo" in this example, assigned to the variable'sample'

3. Execute the code block and print the value of the variable "sample" as "Foo"

4. __exit__() method is called

The real power of with is that it can handle exceptions. You may have noticed that the __exit__ method of the Sample class has three parameters-val, type and trace. These parameters are quite useful in exception handling. Let's change the code and see how it works.

#!/usr/bin/env python

# with_example02.py

 class Sample:

    def __enter__(self):

        return self

    def __exit__(self, type, value, trace):

        print "type:", type

        print "value:", value

        print "trace:", trace

    def do_something(self):

        bar = 1/0

        return bar + 10

with Sample() as sample:

    sample.do_something()

In this example, get_sample() after with becomes Sample(). This doesn't matter, as long as the object returned by the statement following with has __enter__() and __exit__() methods. In this example, the __enter__() method of Sample() returns the newly created Sample object and assigns it to the variable sample.

After the code is executed:

bash-3.2$ ./with_example02.py

type: <type 'exceptions.ZeroDivisionError'>

value: integer division or modulo by zero

trace: <traceback object at 0x1004a8128>

Traceback (most recent call last):

File "./with_example02.py", line 19, in <module>

    sample.do_something()

File "./with_example02.py", line 15, in do_something

    bar = 1/0

ZeroDivisionError: integer division or modulo by zero

In fact, when any exception is thrown in the code block following with, the __exit__() method is executed. As the example shows, when an exception is thrown, the associated type, value, and stack trace are passed to the __exit__() method, so the ZeroDivisionError thrown is printed. When developing the library, operations such as cleaning up resources, closing files, etc., can all be placed in the __exit __ method.

Therefore, Python's with statement provides an effective mechanism to make the code more concise, and at the same time, it is easier to clean up when an exception occurs.

Guess you like

Origin blog.csdn.net/Python_xiaobang/article/details/112693366