Day 31 - Understanding Generators

Hmmm.

Ran into something yesterday while going through section 3 of the Python Next Level course- generator functions. A Python generator, as defined here , is a function/method that is declared in a way that makes it iterable.

What?

Why would I do that? While I understand that it does, what makes it ‘click’ for me is understanding an obvious use case. Take a look at one of the method implementations in the course:

def get_server():
    def f():
        while True:
            i = SERVERS.pop(0)
            SERVERS.append(i)
            yield i
    return next(f())

Please tell me if I am not understanding how this works…so, this get_server method defines an internal method that pops off the elements of the SERVER array (which is just an array of strings), and assigns them to ‘i’. Then, it assigns the element back to the end of the array, which gives me this infinite looping effect. Becuase we’ve used ‘yield’ on the ‘i’ variable, I’m able to iterate serially through the array to get the next value contained in the array.

I think I’ve got it, but can anyone offer me other use cases where it makes sense to use generators?

Don’t worry, I’ll wait.

Jason T Clark

Jason T Clark

Father. Musician. Gamer. Coder.

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin