当前位置:  开发笔记 > 编程语言 > 正文

在python中结合'with'和'yield'是否安全?

如何解决《在python中结合'with'和'yield'是否安全?》经验,为你挑选了2个好方法。

在python中使用上下文管理器自动关闭文件是一个常见的习惯用法:

with open('filename') as my_file:
    # do something with my_file

# my_file gets automatically closed after exiting 'with' block

现在我想读几个文件的内容.数据的使用者不知道或不关心数据是来自文件还是非文件.它不想检查它收到的对象是否可以打开.它只是想从中获取内容.所以我创建了一个像这样的迭代器:

def select_files():
    """Yields carefully selected and ready-to-read-from files"""
    file_names = [.......]
    for fname in file_names:
        with open(fname) as my_open_file:
            yield my_open_file

这个迭代器可以像这样使用:

for file_obj in select_files():
    for line in file_obj:
        # do something useful

(注意,可以使用相同的代码来消耗不是打开的文件,而是使用字符串列表 - 这很酷!)

问题是:产生打开文件是否安全?

看起来像"为什么不呢?".消费者调用迭代器,迭代器打开文件,将其产生给消费者.消费者处理文件并返回下一个迭代器.迭代器代码恢复,我们退出'with'块,my_open_file对象关闭,转到下一个文件等.

但是,如果消费者永远不会回到下一个文件的迭代器呢?消费者内部发生异常.或者消费者在其中一个文件中发现了一些非常令人兴奋的内容,并愉快地将结果返回给任何人调用它?

迭代器代码在这种情况下永远不会恢复,我们永远不会到'with'块结束,my_open_file对象永远不会被关闭!

或者是吗?



1> mgilson..:

你提出了一个在1之前提出的批评.在这种情况下的清理是不确定的,但是当生成器被垃圾收集时,它将CPython中发生. 其他python实现的里程可能会有所不同......

这是一个简单的例子:

from __future__ import print_function
import contextlib

@contextlib.contextmanager
def manager():
    """Easiest way to get a custom context manager..."""
    try:
        print('Entered')
        yield
    finally:
        print('Closed')


def gen():
    """Just a generator with a context manager inside.

    When the context is entered, we'll see "Entered" on the console
    and when exited, we'll see "Closed" on the console.
    """
    man = manager()
    with man:
        for i in range(10):
            yield i


# Test what happens when we consume a generator.
list(gen())

def fn():
    g = gen()
    next(g)
    # g.close()

# Test what happens when the generator gets garbage collected inside
# a function
print('Start of Function')
fn()
print('End of Function')

# Test what happens when a generator gets garbage collected outside
# a function.  IIRC, this isn't _guaranteed_ to happen in all cases.
g = gen()
next(g)
# g.close()
print('EOF')

在CPython中运行此脚本,我得到:

$ python ~/sandbox/cm.py
Entered
Closed
Start of Function
Entered
Closed
End of Function
Entered
EOF
Closed

基本上,我们看到的是,对于耗尽的生成器,上下文管理器会在您预期时进行清理.对于耗尽的发电机,当垃圾收集器收集发电机时,清理功能运行.当发电机超出范围(或gc.collect最迟在下一个周期的IIRC)时会发生这种情况.

但是,做一些快速实验(例如运行上面的代码pypy),我没有清理所有的上下文管理器:

$ pypy --version
Python 2.7.10 (f3ad1e1e1d62, Aug 28 2015, 09:36:42)
[PyPy 2.6.1 with GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)]
$ pypy ~/sandbox/cm.py
Entered
Closed
Start of Function
Entered
End of Function
Entered
EOF

因此,上下文管理器__exit__ 将为所有python实现调用的断言是不真实的.可能这里的失误可归因于pypy的垃圾收集策略(这不是引用计数),并且到时候pypy决定收割发电机,这个过程已经关闭了,因此,它没有打扰它...在大多数情况下现实世界的应用程序,发电机可能会很快收到并最终确定,实际上并不重要......


提供严格的保证

如果您想保证您的上下文管理器已正确完成,您应该在完成后关闭生成器2.取消注释g.close()上面的行给了我确定性清理,因为GeneratorExityield语句中引发了一个(在上下文管理器中)然后它被生成器捕获/抑制了......

$ pypy ~/sandbox/cm.py
Entered
Closed
Start of Function
Entered
Closed
End of Function
Entered
Closed
EOF

$ python3 ~/sandbox/cm.py
Entered
Closed
Start of Function
Entered
Closed
End of Function
Entered
Closed
EOF

$ python ~/sandbox/cm.py
Entered
Closed
Start of Function
Entered
Closed
End of Function
Entered
Closed
EOF

FWIW,这意味着您可以使用contextlib.closing以下方法清理发电机:

from contextlib import closing
with closing(gen_function()) as items:
    for item in items:
        pass # Do something useful!

1最近,一些讨论围绕着PEP 533,其目的是使迭代器清理更具确定性.
2关闭已经关闭和/或消耗的发电机是完全可以的,这样您就可以调用它而不必担心发电机的状态.



2> Aaron Hall..:
在python中结合'with'和'yield'是否安全?

我认为你不应该这样做.

让我演示制作一些文件:

>>> for f in 'abc':
...     with open(f, 'w') as _: pass

说服自己,文件在那里:

>>> for f in 'abc': 
...     with open(f) as _: pass 

这是一个重新创建代码的函数:

def gen_abc():
    for f in 'abc':
        with open(f) as file:
            yield file

在这里看起来你可以使用这个功能:

>>> [f.closed for f in gen_abc()]
[False, False, False]

但是,让我们首先创建所有文件对象的列表解析:

>>> l = [f for f in gen_abc()]
>>> l
[<_io.TextIOWrapper name='a' mode='r' encoding='cp1252'>, <_io.TextIOWrapper name='b' mode='r' encoding='cp1252'>, <_io.TextIOWrapper name='c' mode='r' encoding='cp1252'>]

现在我们看到它们都已关闭:

>>> c = [f.closed for f in l]
>>> c
[True, True, True]

这仅在发电机关闭之前有效.然后文件全部关闭.

我怀疑这是你想要的,即使你正在使用延迟评估,你的最后一个文件可能会在你使用它之前关闭.

推荐阅读
勤奋的瞌睡猪_715
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有