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