Issue
I would like you to consider the following code:
def func(alist):
if len(alist) == 1:
return arg * 2
for item in alist:
yield item * 2
When I run it, I get this error:
SyntaxError: 'return' with argument inside generator
Now, I realize that I cannot do this. However, I would like to know why. What exactly is going on behind the scenes that is causing Python to throw the SyntaxError
?
Solution
Python has to decide whether a function is a generator at bytecode compilation time. This is because the semantics of generators say that none of the code in a generator function runs before the first next
call; the generator function returns a generator iterator that, when next
is called, runs the generator code. Thus, Python can't decide whether a function should be a generator or not by running it until it hits a yield
or a return
; instead, the presence of a yield
in a function signals that the function is a generator.
Answered By - user2357112
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.