5

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?

5
  • No. Generators and normal functions are different beasts from the moment of compilation. Commented May 28, 2018 at 17:49
  • 1
    The mere presence of a 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". Commented May 28, 2018 at 17:49
  • Consider, def g(): print('foo'); yield 1. If you do x = g() you won't see anything printed. Commented May 28, 2018 at 17:50
  • "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." Any function with a yield will return a generator when called. When you subsequently start that generator, it will run until hitting a yield. Commented May 28, 2018 at 17:52
  • By calling a function that contains a yield statement, you are creating a generator. That is why the content don't get executed unless you call next on it. But without the yield it would be a normal function that executes those lines once you call it. Commented Aug 8, 2023 at 14:06

2 Answers 2

1

When a function has a yield, even if it is not reachable, it will be a generator.

1

The thing here is the yield statement. When you use yield inside a function, it will create a generator. Keep in mind that any function with a yield will return a generator when called.

Try this:

def func():
    print("> Why doesn't this line print?")
    exit()

x = func()
print(x)

Results:

Why doesn't this line print?
None

And then the program exits.

Not the answer you're looking for? Browse other questions tagged or ask your own question.