python创建解释器失败_为什么Python解释器没有隐式创建生成器?

本文探讨了Python中生成器函数的使用,特别是当包含条件语句时的情况。生成器在遇到`yield`语句时会变成一个特殊的函数类型。解释器不允许隐式将注释的代码转换为实际代码,因为这可能导致复杂性和不一致性。例如,条件可能应在生成器迭代的特定时刻执行,或者在函数调用时立即执行。提供的代码示例展示了如何明确地处理这种情况,返回一个字符串或生成器,这取决于参数的值。
摘要由CSDN通过智能技术生成

#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))

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.

解决方案

The reason is simply, if the def contains a yield statement, it creates a 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.

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")

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值