gpt4 book ai didi

python - 生成器和文件

转载 作者:太空狗 更新时间:2023-10-30 01:56:59 25 4
gpt4 key购买 nike

当我写的时候:

lines = (line.strip() for line in open('a_file'))

文件是立即打开还是仅在我开始使用生成器表达式时才访问文件系统?

最佳答案

open() 在构建生成器时立即被调用,无论您何时或是否使用它。

相关规范是PEP-289 :

Early Binding versus Late Binding

After much discussion, it was decided that the first (outermost) for-expression should be evaluated immediately and that the remaining expressions be evaluated when the generator is executed.

Asked to summarize the reasoning for binding the first expression, Guido offered [5]:

Consider sum(x for x in foo()). Now suppose there's a bug in foo() that raises an exception, and a bug in sum() that raises an exception before it starts iterating over its argument. Which exception would you expect to see? I'd be surprised if the one in sum() was raised rather the one in foo(), since the call to foo() is part of the argument to sum(), and I expect arguments to be processed before the function is called.

OTOH, in sum(bar(x) for x in foo()), where sum() and foo() are bugfree, but bar() raises an exception, we have no choice but to delay the call to bar() until sum() starts iterating -- that's part of the contract of generators. (They do nothing until their next() method is first called.)

有关进一步讨论,请参阅该部分的其余部分。

关于python - 生成器和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45758426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com