Python 3.6 [PY36 Env]

Understanding Python Yield Command

This document explores the use of the yield keyword. This command exists in other languages too (C# and .NET among them). Code in the next cell was excerpted from a StackOverflow post. Comments were then added after running a quick test.


In [2]:
def f123():
    yield 1
    yield 2
    yield 3

for item in f123():
    print(item)     # by iterating over the "generator object" this function returns, we see the answers
                    # yield is adding results into a generator object that the function will then return


1
2
3

In [3]:
f123()  # note:  returns a generator object that each yield added content to


Out[3]:
<generator object f123 at 0x0000000004716A98>

Here's another demo from StackOverflow showing that a function using yield does not have to terminate and can be used in code as shown here. Author indicates this can help solve certain tricky situations. Testing and experimentation with this has not been undertaken yet.


In [5]:
def fib():
    last, cur = 0, 1
    while True: 
        yield cur
        last, cur = cur, last + cur

def psuedo_code_doNotRunWithoutFixingIt():
    some_condition = False  # added so this cell won't throw an error
                            # edit and implement what follows to make use of this example
        
    for f in fib():
        if some_condition: break
        # coolfuncs(f);     # do something here ... author wrote it as coolfuncs(f);

In [4]:
# implementing the pseudocode just to show it in action ...
# this may not represent best practice but could be useful in the field ...

def fib():
    last, cur = 0, 1
    while True: 
        yield cur
        last, cur = cur, last + cur

def x_toThe_x(x):
    return x**x
        
def testCodeFor_fib():
    some_condition = 13  
    
    loopCount = 0
    for f in fib():
        print("Starting loop %d with f of %d." %(loopCount, f))
        if f >= some_condition:
            print("Termination point reached, exiting loop.")
            break
        print("%d raised to the %d power: %d" %(f,f, x_toThe_x(f)))  # do stuff here, this is an example
        loopCount +=1
        
# test the code
testCodeFor_fib()


Starting loop 0 with f of 1.
1 raised to the 1 power: 1
Starting loop 1 with f of 1.
1 raised to the 1 power: 1
Starting loop 2 with f of 2.
2 raised to the 2 power: 4
Starting loop 3 with f of 3.
3 raised to the 3 power: 27
Starting loop 4 with f of 5.
5 raised to the 5 power: 3125
Starting loop 5 with f of 8.
8 raised to the 8 power: 16777216
Starting loop 6 with f of 13.
Termination point reached, exiting loop.

In [ ]: