lambda 中生成器的行为可以安全应对未来的变化吗?
我有以下函数:
| def line_reader_iter(file_object):
| while True:
| a_line = file_object.readline()
| if len(a_line)==0: raise StopIteration
| yield a_line[:-1]
在某处我说:
| line_reader = lambda: next(line_reader_iter(infile))
显然, lambda 之所以有效,是因为编译时与运行时行为似乎存在差异,这是非常受欢迎的: line_reader_iter() 放置对迭代器对象的引用到 lambda 表达式中,而不是在每次计算 lambda 时创建生成器对象。但是:这是可移植且稳定的行为吗?我只是一个Python新手,我不知道我的代码相对于Python执行模型是否处于灰色地带。有人可以启发我吗?
斯拉尔蒂
I have the following function:
| def line_reader_iter(file_object):
| while True:
| a_line = file_object.readline()
| if len(a_line)==0: raise StopIteration
| yield a_line[:-1]
and somewhere I say:
| line_reader = lambda: next(line_reader_iter(infile))
Clearly, the lambda only works because there seems to be a difference in compile-time vs. run-time behaviour which is very welcome: the line_reader_iter() puts the reference to the iterator object into the lambda expression instead of the creation of a generator object each time the lambda is evaluated. BUT: is this portable and stable behaviour? I am just a Python novice and I don't know if my code is in a grey area with respect to the Python execution model. Can someone enligthen me?
slarti
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你实际上误解了为什么这有效。每次调用
line_reader()
时,都会创建一个新的line_reader_iter
生成器。它似乎有效,因为您每次都使用相同的infile
,并且每次调用readline()
都会返回文件的下一行。考虑以下更简单的示例:
您可以通过使用以下命令获得您想要的行为:
以下是这如何与我的范围示例一起使用:
I think you are actually misunderstanding why this works. Each time you call
line_reader()
a newline_reader_iter
generator is created. It appears to work because you use the sameinfile
each time, and each call toreadline()
will return the next line of the file.Consider the following simpler example:
You can get the behavior you want by using the following:
Here is how this would work with my range example: