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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值