为什么Python解释器没有隐式创建生成器? [英] Why doesn't the Python interpreter implicitly create the generator?

查看:110
本文介绍了为什么Python解释器没有隐式创建生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#def func(param):
#    if param < 0:
#        return "test"
#    i = 0
#    while i < param:
#        yield i
#        i += 1
def func(param):
    if param < 0:
        return "test"
    def gen(n):
        i = 0
        while i < param:
            yield i
            i += 1
    return gen(param)

print(func(-1))
print(func(3))
g = func(3)
for i in range(0, 3):
    print(next(g))

是否存在Python解释器无法将注释的代码隐式转换为实际代码的原因?似乎应该允许这样做,但我想知道是什么造成了他们选择不允许这样做的影响.

Is there a reason that the Python interpreter can not convert the commented code to the actual code implicitly? This seems like this should be allowed, but I am wondering what repercussions there are that made them choose to disallow this.

推荐答案

原因很简单,如果def包含yield语句,它将创建一个生成器:

The reason is simply, if the def contains a yield statement, it creates a generator:

http://www.python.org/dev/peps/pep-0255/

yield语句只能在函数内部使用.一个功能 包含一个yield语句的函数称为生成器函数.发电机 函数在所有方面都是普通的函数对象,但具有 在代码对象的co_flags成员中设置了新的CO_GENERATOR标志.

The yield statement may only be used inside functions. A function that contains a yield statement is called a generator function. A generator function is an ordinary function object in all respects, but has the new CO_GENERATOR flag set in the code object's co_flags member.

这就是解释器如何区分常规函数和生成器函数的方式.它易于实现,易于推理(如果包含yield,则是生成器")

That is how the interpreter distinguishes between a regular function, and a generator function. It's simple to implement, easy to reason about ("if it contains a yield, it's a generator")

您描述的条件生成器"行为实施起来会更加复杂,并且在某些情况下是不希望的(可能是条件生成器在第一次生成迭代内发生,或者它应该在您调用func(...))

The "conditional generator" behaviour you describe would be much more complex to implement, and in some cases not desirable (maybe the conditional should happen inside the first iteration of the generator, or maybe it should run as soon as you call func(...))

您的其他代码要么返回一个生成器,要么返回一个字符串.如果这是您想要的界面,那么这似乎是一个完美的解决方案(但如果没有实际的示例,很难提出实用的建议)

Your other code either returns a generator, or a string. If that's the interface you want, it seems like a perfectly good solution (but it's hard to make practical suggestions without a real example)

这篇关于为什么Python解释器没有隐式创建生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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