Python中的产量中断 [英] yield break in Python

查看:101
本文介绍了Python中的产量中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据对此问题的回答, C#中的yield break等同于Python中的return.在正常情况下,return确实会停止生成器.但是,如果您的函数只执行return,则将得到一个None而不是一个空的迭代器,该迭代器由C#中的yield break返回

According to answer to this question, yield break in C# is equivalent to return in Python. In the normal case, return indeed stops a generator. But if your function does nothing but return, you will get a None not an empty iterator, which is returned by yield break in C#

def generate_nothing():
    return

for i in generate_nothing():
    print i

您将获得一个TypeError: 'NoneType' object is not iterable, 但是,如果我添加并且从未在return之前运行yield,则此函数将返回我期望的结果.

You will get a TypeError: 'NoneType' object is not iterable, but if I add and never run yield before return, this function returns what I expect.

def generate_nothing():
    if False: yield None
    return

它有效,但看起来很奇怪.你有更好的主意吗?

It works, but seems weird. Do you have a better idea?

推荐答案

def generate_nothing():
    return
    yield

这篇关于Python中的产量中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆