Dada
|> Structures
|> Algorithms

Python's yield

Some notes on what it is and how it works

The short answer

Python's 'yield' is used instead of 'result' when you are creating results via a generator function. Think of generators as some sort of a lazy, stateful function that returns one item at a time. Why would we want that? We would want this when consuming a huge amount of data that can't be loaded all at once into memory. Think of a giant csv file.

So the point of a generator is to have a function that can give you one item at a time and remember where it was the next time you call it.

Here is an example:

    >>> # we create our generator
    >>> def up_to_10():
    ...   for n in range(10):
    ...     yield n
    ...
    >>> # we use it 
    >>> for i in up_to_10():
    ...   print(i)
    ...
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    >>>

The longer story

My example seems silly since we could achieve the same with a range or with a list. My guess is that generators are useful to implement laziness. You could create a library that queries a database, but will only make the call it when you actually need it. I can also see how we can use generators to create infinite series.

'yield' trips me up coming from Ruby. 'yield' does something different in Ruby: it executes a block that has been passed to the method.

Python's 'yield' seems closer to C#'s yield. Sadly, I never fully understood C#'s yield. From this blog, it looks like it is similar to Pyton's yield. https://www.kenneth-truyers.net/2016/05/12/yield-return-in-c/[3]

You can read more about 'yield' and generators at https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/[1] and at its PEP[2]

References:

[1] A. Agarwal, "When to use yield instead of return in Python?" GeeksForGeeks. https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/ (accessed July 30, 2020)

[2] N. Schemenauer, T. Peters, M. Lie Hetland, PEP 255. Python https://www.python.org/dev/peps/pep-0255/(accessed July 30, 2020)

[3] K. Truyers, Yield return in C#, kenneth-truyers.net, https://www.kenneth-truyers.net/2016/05/12/yield-return-in-c/(accessed July 31, 2020)