Understand Python “yield”, An interrupt, A trap, A scissor

Andrew Zhu (Shudong Zhu)
Geek Culture
Published in
4 min readAug 2, 2021

--

Some said “yield” is similar to the usage of “return”, the answer could be both yes and no. But one thing is certain: yield is not return.

What is yield in Python?

The keyword “yield” working like a scissor cut the program into two parts.

The keyword “yield” working like an interrupt in OS, yield will return the control of the program back to the caller.

The keyword “yield” not only gives control back to the caller, but it can also “return” back some data(generator), and receive data from the caller(coroutine).

yield as a program scissor

A Sample

Define a function with yield:

def func():
print('start')
item = yield 123
print('end')

run with:

f = func()

But… nothing happened. The message “start end” is not printed out.

Why? because when there are any yield keywords in a function, the function will be treated as a generator by the Python interpreter.

print(f)

The above print will return something like this:

<generator object func at 0x7f9cd131e3c0>

--

--