python - 最后在 Python 3 生成器中尝试

标签 python python-3.x generator try-except

我见过一段 Python 3 代码:

def gen():
    try:
        while True:
            yield 1
    finally:
        print("stop")

print(next(gen()))

运行之后,我一开始以为输出应该是:

1

但实际上结果是:

stop
1

这怎么会发生?幕后发生了什么?

如果我运行 for i in gen(): print(i),将会出现一个无限循环,这正是我所期望的。这里的fornext有什么区别?

最佳答案

finally 子句正在生成器对象的垃圾回收中执行。

考虑以下两种情况:

def gen():
    try:
        while True:
            yield 1
    finally:
        print("stop")

g1 = gen(); print('first time')
print(next(g1))
g2 = gen(); print('second time')  # no stop will be printed because we haven't hit the finally clause yet
def gen():
    try:
        while True:
            yield 1
    finally:
        print("stop")

g = gen(); print('first time')
print(next(g))
g = gen(); print('second time')   # stop will be printed when the first object g was assigned to is garbage collected

关于python - 最后在 Python 3 生成器中尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56062909/

相关文章:

python - 如何使用三个列表创建所有排列? Python

python - 如何实例化变量?

python - python 调试器中的所有变量都未定义

python - 在 for 循环中使用生成器 send()

css - 渐变文字颜色

python - 将 Flower 部署到 Heroku

python - 如何对pandas多索引中的列进行操作

python - 如何修复Python中的 "<string> DeprecationWarning: invalid escape sequence"?

python - 如何从csv文件中读取某一列?

python - numpy.random 与 numpy.random.Generate 之间有什么区别