欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python基础知识(2020/8/21)

程序员文章站 2024-03-15 15:07:29
...

Python keyword ‘with’

Prolem

Many operations like opening file or acquiring some sort of external resource need 'try-finally' in order to ensure the code in finally block to be excuted. 'With' is designed to simplify the use of 'try finally'.

e.g. After we open a file, we have to close it. But if something gets wrong when we operate that file then the file may not be closed on time.
Here comes ‘try finally’:

set things up
    try:
        do something
    finally:
        tear things down

But it is verbose to to write this code everytime you need. GvR and the python-dev team finally came up with a generalization of the latter, using an object to control the behaviour of an external piece of code

Solution

    class controlled_execution:
        def __enter__(self):
            set things up
            return thing
        def __exit__(self, type, value, traceback):
            tear things down

    with controlled_execution() as thing:
         some code

Now, when the “with” statement is executed, Python evaluates the expression, calls the enter method on the resulting value (which is called a “context guard”), and assigns whatever enter returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s exit method.
As an extra bonus, the exit method can look at the exception, if any, and suppress it or act on it as necessary. To suppress the exception, just return a true value.

Example

  1. torch.no_grad
class no_grad(_DecoratorContextManager):
	def __enter__(self):
		self.prev = toch.is_rad_enabled()
		torch._C.set_grad_enabled(False)
	def __exit__(self, *args):
		torch.set_grad_enabled(self.prev)
		return False

Parameters’ grad in this contexManager are ignored.

  1. file
with open(path) as f:
	do something

The file instatnce f will be closed in __exit__ method

相关标签: python