- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
当我写的时候:
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 infoo()
that raises an exception, and a bug insum()
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 insum()
was raised rather the one infoo()
, since the call tofoo()
is part of the argument tosum()
, and I expect arguments to be processed before the function is called.OTOH, in
sum(bar(x) for x in foo())
, wheresum()
andfoo()
are bugfree, butbar()
raises an exception, we have no choice but to delay the call tobar()
untilsum()
starts iterating -- that's part of the contract of generators. (They do nothing until theirnext()
method is first called.)
有关进一步讨论,请参阅该部分的其余部分。
关于python - 生成器和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45758426/
我是一名优秀的程序员,十分优秀!