If you run the following snippet, it will ignore the 'print' on line 2 and 'exit' on line 3. However, if you comment out the already unreachable 'yield' from line 4, lines 2 and 3 will execute normally.
This makes me think that Python (3.5.2) looks for a 'yield' anywhere in the function, and if one is found, even an unreachable one, nothing is executed until a next() is called on the returned iterator. Up until now, I was under the impression that the function would execute normally up until hitting a yield, at which point it would begin acting like an iterator.
def func():
print("> Why doesn't this line print?")
exit() # Within this function, nothing should matter after this point. The program should exit
yield "> The exit line above will exit ONLY if you comment out this line."
x = func()
print(x)
Does this seem strange to anyone else? Does anybody have some insight to share here?
yield
statement turns a function into a generator. Note the bolded text in the linked question/answer: "When you call the function, the code you have written in the function body does not run".def g(): print('foo'); yield 1
. If you dox = g()
you won't see anything printed.yield
statement, you are creating a generator. That is why the content don't get executed unless you callnext
on it. But without theyield
it would be a normal function that executes those lines once you call it.