Iterables: A Crazy, Crazy World Pt 2
Part 2: What are these crazy functions?
In case you haven't already read part 1: here it is.
So firstly, like @pyelias said, it's not actually an "iterator", it's a type of iterator called a "generator". But I'm just going to be calling it an iterator. Just keep in mind that you can make classes that are iterators too.
> type(simple_range(0, 4)) <class 'generator'>
By the way, we are using the same
simple_range definition as the previous tutorial.
After the last tutorial's use of
for, you may be wondering if there is a way to iterate without that. You're in luck, there is, and that's what we will be using a little in this tutorial.
> f = simple_range(0, 4) > next(f) 0 > next(f) 1 > next(f) 2 > next(f) 3 > next(f) ERROR: "StopIteration"
The first nice thing we want to cover is
So, of course we get help for it!
> help(f.close) close(...) method of builtins.generator instance close() -> raise GeneratorExit inside generator.
An example for how this could be used is this:
def simple_counter(start=0): x = start while True: yield x x += 1 gen = simple_counter() for i in gen: print(i) if i == 5: # exit the loop without `break` gen.close()
All good right?
Now, let's skip a bunch of methods, to arrive to the next method we will look at,
.gi_* methods are beyond the scope of this tutorial, and are used for documentation / figuring out what a generator's code is.
> f = simple_counter(0, 4) > help(f.send) send(...) method of builtins.generator instance send(arg) -> send 'arg' into generator, return next yielded value or raise StopIteration.
Well, that sounds useful. Let's take the previous example and modify it slightly to make it better.
def simple_counter(start=0): x = start while True: inc = yield x x += inc or 1 gen = simple_counter() next(gen) # returns 0 next(gen) # returns 1 gen.send(3) # returns 4 next(gen) # returns 5
By the way, the
variable or 1 trick just saves an if statement checking if
I highly recommend reading this stackoverflow answer about
yield from. In fact, the next tutorial will make the assumption that you have read it.