Python yield使用详解(二)

上下文管理器和with块

with表达式

常见的with用法格式:

    with open(filename) as f:
        statement
        statement
     ...
    with lock:
        statement
        statement
     ...
  • 控制代码块的进入/退出

定制你自己的上下文管理器

一个计时器的例子:

import time
from contextlib import contextmanager

@contextmanager
def timethis(label):
    start = time.time()
    try:
        yield 
    finally:
        end = time.time()
        print('%s: %0.3f' % (label, end-start))
        
#Usage
with timethis('counting'):
     n = 1000000
     while n > 0:
         n -= 1
#Output
counting: 0.156

另外一个例子:临时文件夹

import tempfile, shutil
from contextlib import contextmanager
@contextmanager
def tempdir():
    outdir = tempfile.mkdtemp()
    try:
        yield outdir
    finally:
        shutil.rmtree(outdir)
        
#Example
with tempdir() as dirname:
    ...

等等!!!
这里的yield outdir是什么?

  • 不是迭代
  • 不是数据流
  • 不是并发
  • 那是什么???

深入上下文管理器

现在可以对上面内容进行小结一下:

  • 上下文对象存在的目的是管理with语句,就像迭代器的存在是为了管理for语句
  • with语句的目的是简化ttry/finally模式,这种模式用于保证一段代码运行完毕后执行某项操作。即使那段代码由于异常,return语句或sys.exit()调用而终止,也会执行指定操作

上下文管理器的内部实现:

  • 上下文管理器协议包含enterexit两个方法,with语句还是运行时,会在上下文管理器对象上调用enter方法。with语句结束后,会在上下文管理器对象上调用exit方法,以此扮演finally子句的角色

实现模板

class Manager(object):
    def __enter__(self):
        return value
    def __exit__(self, exc_type, val, tb):
        if exc_type is None:
            return
        else:
            # Handle an exception (if you want)
           return True if handled else False
           
 # Usage         
with Manager() as value:
    statements
    statements

实例

import tempfile
import shutil
class tempdir(object):
    def __enter__(self):
        self.dirname = tempfile.mkdtemp()  #生成临时文件夹
        return self.dirname
    def __exit__(self, exc, val, tb):
        shutil.rmtree(self.dirname)   #删除文件夹
    
# Usage  
with tempdir() as dirname:
...
# with语句运行完毕后,会自动删除那个临时文件夹

更简洁的一种选择:利用@contextmanager装饰器

import tempfile, shutil
from contextlib import contextmanager
@contextmanager
def tempdir():
    dirname = tempfile.mkdtemp()
    try:
        yield dirname
    finally:
        shutil.rmtree(dirname)
 # 跟上个例子相同的代码。

contextmanager装饰器运行原理

下图:

  • 思考剪刀处yield代码
  • 将代码一分两半

  • 每一半对应着上下文管理器协议
  • yield是促成图中这一实现的魔法

这里有一个注意点:使用@contextmanager装饰器时,要把yield语句放在try/finally语句中,这是无法避免的,因为我们永远不知道上下文管理器的用户会在with中做什么(会引发一些python解释器能捕获到的错误)。
当然,想要你如果想要更加深入的了解@contextmanager的内部代码实现,可以查看源代码,这里不展开了。

总结

  1. yield表达式的另一个不同作用:上下文管理器
  2. 常用来重新定制控制流
  3. 也可以用@contextmanager装饰器来代替enterexit两个方法。优雅且实用,把三个不同的Python特性结合到一起: 函数装饰器,生成器和with语句

参考资料

David beazley协程
Fluent Python



作者:寻找无双丶
链接:https://www.jianshu.com/p/bf887cae4d8e
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/qq_37312720/article/details/83831621