lambda 中生成器的行为可以安全应对未来的变化吗?

发布于 2024-12-07 05:52:36 字数 530 浏览 0 评论 0原文

我有以下函数:

|    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

日暮斜阳 2024-12-14 05:52:36

我认为你实际上误解了为什么这有效。每次调用 line_reader() 时,都会创建一个新的 line_reader_iter 生成器。它似乎有效,因为您每次都使用相同的 infile,并且每次调用 readline() 都会返回文件的下一行。

考虑以下更简单的示例:

>>> counter = lambda: next(iter(range(10)))
>>> counter()
0
>>> counter()    # each time the lambda is called, a new range iter is created
0

您可以通过使用以下命令获得您想要的行为:

line_reader = line_reader_iter(infile).next

以下是这如何与我的范围示例一起使用:

>>> counter = iter(range(10)).next
>>> counter()
0
>>> counter()    # yay, we are actually using the same iterator
1

I think you are actually misunderstanding why this works. Each time you call line_reader() a new line_reader_iter generator is created. It appears to work because you use the same infile each time, and each call to readline() will return the next line of the file.

Consider the following simpler example:

>>> counter = lambda: next(iter(range(10)))
>>> counter()
0
>>> counter()    # each time the lambda is called, a new range iter is created
0

You can get the behavior you want by using the following:

line_reader = line_reader_iter(infile).next

Here is how this would work with my range example:

>>> counter = iter(range(10)).next
>>> counter()
0
>>> counter()    # yay, we are actually using the same iterator
1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文