What is the use of theyieldkeyword in Python? What does it do?
For example, I'm trying to understand this code (**):
def node._get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
And this is the caller:
result, candidates = list(), [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
What happens when the method_get_child_candidatesis called? A list is returned? A single element is returned? Is it called again? When subsequent calls do stop?
** The code comes from Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source:Module mspace.
正确答案 To understand whatyielddoes, you must understand what generators are. And before generators come iterables.
Iterables
When you create a list, you can read its items one by one, and it's called iteration:
>>> mylist = [1, 2, 3]
>>> for i in mylist:
... print(i)
1
2
3
Mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:
>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
... print(i)
0
1
4
Everything you can use "for... in..." on is an iterable: lists, strings, files... These iterables are handy because you can read them as much as you wish, but you store all the values in memory and it's not always what you want when you have a lot of values.
Generators
Generators are iterators, butyou can only iterate over them once. It's because they do not store all the values in memory,they generate the values on the fly:
>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
... print(i)
0
1
4
It is just the same except you used()instead of[]. BUT, you can not performfor i in mygeneratora second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.
Yield
Yieldis a keyword that is used likereturn, except the function will return a generator.
>>> def createGenerator():
... mylist = range(3)
... for i in mylist:
... yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
... print(i)
0
1
4
Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.
To masteryield, you must understand thatwhen you call the function, the code you have written in the function body does not run.The function only returns the generator object, this is a bit tricky :-)
Then, your code will be run each time theforuses the generator.
Now the hard part:
The first time theforcalls the generator object created from your function, it will run the code in your function from the beginning until it hitsyield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return.
The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to an end, or because you do not satisfy a "if/else" anymore.
Your code explained
Generator:
# Here you create the method of the node object that will return the generator
def node._get_child_candidates(self, distance, min_dist, max_dist):
# Here is the code that will be called each time you use the generator object:
# If there is still a child of the node object on its left
# AND if distance is ok, return the next child
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
# If there is still a child of the node object on its right
# AND if distance is ok, return the next child
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
# If the function arrives here, the generator will be considered empty
# there is no more than two values: the left and the right children
Caller:
# Create an empty list and a list with the current object reference
result, candidates = list(), [self]
# Loop on candidates (they contain only one element at the beginning)
while candidates:
# Get the last candidate and remove it from the list
node = candidates.pop()
# Get the distance between obj and the candidate
distance = node._get_dist(obj)
# If distance is ok, then you can fill the result
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
# Add the children of the candidate in the candidates list
# so the loop will keep running until it will have looked
# at all the children of the children of the children, etc. of the candidate
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
This code contains several smart parts:
The loop iterates on a list but the list expands while the loop is being iterated :-) It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case,candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))exhausts all the values of the generator, butwhilekeeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.
Theextend()method is a list object method that expects an iterable and adds its values to the list.
Usually we pass a list to it:
>>> a = [1, 2]
>>> b = [3, 4]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4]
But in your code it gets a generator, which is good because:
You don't need to read the values twice.
You can have a lot of children and you don't want them all stored in memory.
And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples and generators! This is called duck typing and is one of the reason why Python is so cool. But this is another story, for another question...
You can stop here, or read a little bit to see a advanced use of generator:
Controlling a generator exhaustion
>>> class Bank(): # let's create a bank, building ATMs
... crisis = False
... def create_atm(self):
... while not self.crisis:
... yield "$100"
>>> hsbc = Bank() # when everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())
$100
>>> print(corner_street_atm.next())
$100
>>> print([corner_street_atm.next() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
>>> hsbc.crisis = True # crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> wall_street_atm = hsbc.create_atm() # it's even true for new ATMs
>>> print(wall_street_atm.next())
<type 'exceptions.StopIteration'>
>>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business
>>> for cash in brand_new_atm:
... print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...
It can be useful for various things like controlling access to a resource.
Itertools, your best friend
The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator? Chain two generators? Group values in a nested list with a one liner? Map / Zip without creating another list?
Then justimport itertools.
An example? Let's see the possible orders of arrival for a 4 horse race:
Iteration is a process implying iterables (implementing the__iter__()method) and iterators (implementing the__next__()method). Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.
Apart from being in only one line, generators are often faster than regular iterations, and, while they produce the same end result, generators do so very differently than for loops. Also, as some of the later parts of the answer details, generators give much more control over iterations. The yield command uses a generator, for example.– someone-or-otherApr 23 '14 at 4:50
99
I think your explanation of how yield works is a little confusing - a function is not executed from the beginning every time a new value is requested; instead, it is resumed from the same place where it left off last time, which is the line afteryield.– rivApr 27 '14 at 20:06
3
"Generators are iterators, but you can only iterate over them once."- is this a desired feature of a limitation of the language. To me, it seems like a limitation.– jcoSep 1 '14 at 20:04
10
@jco Its a feature, for example, if I had a database with 10k names in it and I wanted to print everyone's name. Using a generator, I could, knowing I wouldn't run out of memory. since once it prints it forgets. If I tried to pull it into a list, I could run out of memory.– triunenatureSep 5 '14 at 8:19
4
As a remark, glob() returns an iterator, while iglob() returns a special iterator(using yield), 'without actually storing them all simultaneously.' seeglob– bookseeSep 7 '14 at 2:19
When you see a function withyieldstatements, apply this easy trick to understand what will happen:
Insert a lineresult = []at the start of the function.
Replace eachyield exprwithresult.append(expr).
Insert a linereturn resultat the bottom of the function.
Yay - no moreyieldstatements! Read and figure out code.
Compare function to original definition.
This trick may give you an idea of the logic behind the function, but what actually happens withyieldis significantly different that what happens in the list based approach. In many cases the yield approach will be a lot more memory efficient and faster too. In other cases this trick will get you stuck in an infinite loop, even though the original function works just fine. Read on to learn more...
Don't confuse your Iterables, Iterators and Generators
First, theiterator protocol- when you write
for x in mylist:
...loop body...
Python performs the following two steps:
Gets an iterator formylist:
Calliter(mylist)-> this returns an object with anext()method (or__next__()in Python 3).
[This is the step most people forget to tell you about]
Uses the iterator to loop over items:
Keep calling thenext()method on the iterator returned from step 1. The return value fromnext()is assigned toxand the loop body is executed. If an exceptionStopIterationis raised from withinnext(), it means there are no more values in the iterator and the loop is exited.
The truth is Python performs the above two steps anytime it wants toloop overthe contents of an object - so it could be a for loop, but it could also be code likeotherlist.extend(mylist)(whereotherlistis a Python list).
Heremylistis aniterablebecause it implements the iterator protocol. In a user defined class, you can implement the__iter__()method to make instances of your class iterable. This method should return aniterator. An iterator is an object with anext()method. It is possible to implement both__iter__()andnext()on the same class, and have__iter__()returnself. This will work for simple cases, but not when you want two iterators looping over the same object at the same time.
So that's the iterator protocol, many objects implement this protocol:
Note that aforloop doesn't know what kind of object it's dealing with - it just follows the iterator protocol, and is happy to get item after item as it callsnext(). Built-in lists return their items one by one, dictionaries return thekeysone by one, files return thelinesone by one, etc. And generators return... well that's whereyieldcomes in:
def f123():
yield 1
yield 2
yield 3
for item in f123():
print item
Instead ofyieldstatements, if you had threereturnstatements inf123()only the first would get executed, and the function would exit. Butf123()is no ordinary function. Whenf123()is called, itdoes notreturn any of the values in the yield statements! It returns a generator object. Also, the function does not really exit - it goes into a suspended state. When theforloop tries to loop over the generator object, the function resumes from its suspended state, runs until the nextyieldstatement and returns that as the next item. This happens until the function exits, at which point the generator raisesStopIteration, and the loop exits.
So the generator object is sort of like an adapter - at one end it exhibits the iterator protocol, by exposing__iter__()andnext()methods to keep theforloop happy. At the other end however, it runs the function just enough to get the next value out of it, and puts it back in suspended mode.
Why Use Generators?
Usually you can write code that doesn't use generators but implements the same logic. One option is to use the temporary list 'trick' I mentioned before. That will not work in all cases, for e.g. if you have infinite loops, or it may make inefficient use of memory when you have a really long list. The other approach is to implement a new iterable classSomethingIterthat keeps state in instance members and performs the next logical step in it'snext()(or__next__()in Python 3) method. Depending on the logic, the code inside thenext()method may end up looking very complex and be prone to bugs. Here generators provide a clean and easy solution.
nice explanation! found it better than the most upvoted answer– RushilMay 31 '14 at 15:40
2
Why is 'yield' harder to understand than most Python constructs? Because of its non-local effect: Normally, when you write 'def xy():' you define a function and bind it to the name xy in the current scope. And this does of course not depend on what is in the body of that function. Not so with 'yield' in the body: Suddenly your definition is NOT a function definition anymore, it is a generator definition. And a generator is a very different thing. (One of the few really ugly aspects of Python in my view.)– Lutz PrecheltSep 16 '14 at 12:33
@LutzPrechelt, it still binds a function that returns a generator to the namexyin the scope. This function returns a generator. This is why a generator can be used withfor x in (y for y in generator):and a function withyieldin it needs to be called asfor x in xy():. This question leaves out "Don't confuse your generators with generator functions," which can be observed in the ATM example in the accepted answer. It is fair to say it makes the keyworddefambiguous to anyone who didn't write the function, but it always is until you findreturnoryieldin the code.– PoikFeb 12 at 14:42
An iterator is just a fancy sounding term for an object that has a next() method. So a yield-ed function ends up being something like this:
Original version:
def some_function():
for i in xrange(4):
yield i
for i in some_function():
print i
This is basically what the python interpreter does with the above code:
class it:
def __init__(self):
#start at -1 so that we get 0 when we add 1 below.
self.count = -1
#the __iter__ method will be called once by the for loop.
#the rest of the magic happens on the object returned by this method.
#in this case it is the object itself.
def __iter__(self):
return self
#the next method will be called repeatedly by the for loop
#until it raises StopIteration.
def next(self):
self.count += 1
if self.count < 4:
return self.count
else:
#a StopIteration exception is raised
#to signal that the iterator is done.
#This is caught implicitly by the for loop.
raise StopIteration
def some_func():
return it()
for i in some_func():
print i
For more insight as to what's happening behind the scenes, the for loop can be rewritten to this:
for-loop expects an iterable (not iterator), therefore an__iter__method must be defined. In case of an iterator object it is very simple:__iter__ = lambda self: self– J.F. SebastianOct 25 '08 at 1:55
__getitem__could be defined instead of__iter__. For example:class it: pass; it.__getitem__ = lambda self, i: i*10 if i < 10 else [][0]; for i in it(): print(i), It will print: 0, 10, 20, ..., 90– J.F. SebastianOct 25 '08 at 2:03
If the compiler detects theyieldkeywordanywhereinside a function, that function no longer returns via thereturnstatement.Instead, itimmediatelyreturns alazy "pending list" objectcalled a generator
A generator is iterable. What is aniterable? It's anything like alistorsetorrangeor dict-view, with abuilt-in protocol for visiting each element in a certain order.
In a nutshell:a generator is a lazy, incrementally-pending list, andyieldstatements allow you to use function notation to program the list valuesthe generator should incrementally spit out.
generator = myYieldingFunction(...)
x = list(generator)
generator
v
[x[0], ..., ???]
generator
v
[x[0], x[1], ..., ???]
generator
v
[x[0], x[1], x[2], ..., ???]
StopIteration exception
[x[0], x[1], x[2]] done
list==[x[0], x[1], x[2]]
Example
Let's define a functionmakeRangethat's just like Python'srange. CallingmakeRange(n)RETURNS A GENERATOR:
def makeRange(n):
# return 0,1,2,...,n-1
i = 0
while i < n:
yield i
i += 1
>>> makeRange(5)
<generator object makeRange at 0x19e4aa0>
To force the generator to immediately return its pending values, you can pass it intolist()(just like you could any iterable):
>>> list(makeRange(5))
[0, 1, 2, 3, 4]
Comparing example to "just returning a list"
The above example can be thought of as merely creating a list which you append to and return:
# list-version # # generator-version
def makeRange(n): # def makeRange(n):
"""return [0,1,2,...,n-1]""" #~ """return 0,1,2,...,n-1"""
TO_RETURN = [] #>
i = 0 # i = 0
while i < n: # while i < n:
TO_RETURN += [i] #~ yield i
i += 1 # i += 1
return TO_RETURN #>
>>> makeRange(5)
[0, 1, 2, 3, 4]
There is one major difference though; see the last section.
How you might use generators
An iterable is the last part of a list comprehension, and all generators are iterable, so they're often used like so:
# _ITERABLE_
>>> [x+10 for x in makeRange(5)]
[10, 11, 12, 13, 14]
To get a better feel for generators, you can play around with theitertoolsmodule (be sure to usechain.from_iterablerather thanchainwhen warranted). For example, you might even use generators to implement infinitely-long lazy lists likeitertools.count(). You could implement your owndef enumerate(iterable): zip(count(), iterable), or alternatively do so with theyieldkeyword in a while-loop.
Please note: generators can actually be used for many more things, such asimplementing coroutinesor non-deterministic programming or other elegant things. However, the "lazy lists" viewpoint I present here is the most common use you will find.
Behind the scenes
This is how the "Python iteration protocol" works. That is, what is going on when you dolist(makeRange(5)). This is what I describe earlier as a "lazy, incremental list".
The built-in functionnext()just calls the objects.next()function, which is a part of the "iteration protocol" and is found on all iterators. You can manually use thenext()function (and other parts of the iteration protocol) to implement fancy things, usually at the expense of readability, so try to avoid doing that...
Minutiae
Normally, most people would not care about the following distinctions and probably want to stop reading here.
In Python-speak, aniterableis any object which "understands the concept of a for-loop" like a list[1,2,3], and aniteratoris a specific instance of the requested for-loop like[1,2,3].__iter__(). Ageneratoris exactly the same as any iterator, except for the way it was written (with function syntax).
When you request an iterator from a list, it creates a new iterator. However, when you request an iterator from an iterator (which you would rarely do), it just gives you a copy of itself.
Thus, in the unlikely event that you are failing to do something like this...
... then remember that a generator is aniterator; that is, it is one-time-use. If you want to reuse it, you should callmyRange(...)again. Those who absolutely need to clone a generator (for example, who are doing terrifyingly hackish metaprogramming) can useitertools.teeif absolutely necessary, since the copyable iterator PythonPEPstandards proposal has been deferred.
I feel like I post a link to this presentation every day: David M. Beazly'sGenerator Tricks for Systems Programmers. If you're a Python programmer and you're not extremely familiar with generators, you should read this. It's a very clear explanation of what generators are, how they work, what the yield statement does, and it answers the question "Do you really want to mess around with this obscure language feature?"
yield is just like return. It returns whatever you tell it to. The only difference is that the next time you call the function, execution starts from the last call to the yield statement.
In the case of your code, the function get_child_candidates is acting like an iterator so that when you extend your list, it adds one element at a time to the new list.
list.extend calls an iterator until it's exhausted. In the case of the code sample you posted, it would be much clearer to just return a tuple and append that to the list.
This is close, but not correct. Every time you call a function with a yield statement in it, it returns a brand new generator object. It's only when you call that generator's .next() method that execution resumes after the last yield.– kuroschOct 24 '08 at 18:11
5
@kurosch: golden comment! That clear, concise explanation of when such functions "resume" or "reset" is enough to useyieldadequately without the need to deeply understand generators' inner mechanics.– MestreLionNov 7 '13 at 4:42
def get_odd_numbers(i):
return range(1, i, 2)
def yield_odd_numbers(i):
for x in range(1, i, 2):
yield x
foo = get_odd_numbers(10)
bar = yield_odd_numbers(10)
foo
[1, 3, 5, 7, 9]
bar
<generator object yield_odd_numbers at 0x1029c6f50>
bar.next()
1
bar.next()
3
bar.next()
5
As you can see, in the first case foo holds the entire list in memory at once. It's not a big deal for a list with 5 elements, but what if you want a list of 5 million? Not only is this a huge memory eater, it also costs a lot of time to build at the time that the function is called. In the second case, bar just gives you a generator. A generator is an iterable--which means you can use it in a for loop, etc, but each value can only be accessed once. All the values are also not stored in memory at the same time; the generator object "remembers" where it was in the looping the last time you called it--this way, if you're using an iterable to (say) count to 50 billion, you don't have to count to 50 billion all at once and store the 50 billion numbers to count through. Again, this is a pretty contrived example, you probably would use itertools if you really wanted to count to 50 billion. :)
This is the most simple use case of generators. As you said, it can be used to write efficient permutations, using yield to push things up through the call stack instead of using some sort of stack variable. Generators can also be used for specialized tree traversal, and all manner of other things.
This example is especially useful because it compares and contrasts usage ofyieldandreturn. Out of all the answers this question received, I thought yours was the best.– JesseBikmanMar 12 '14 at 16:59
Actually, this example doesn't quite demonstrate the difference perfectly, because inyield_odd_numbersyou're usingrangewhich builds up the entire list anyway (in Python 2). If you usedxrangeyouryield_odd_numberswould be efficient. In Python 3,rangeis a generator by default and xrange doesn't exist, so in that case, evenget_odd_numberswould produce a generator.– WidjetFeb 25 at 0:20
For those who prefer a minimal working example, meditate on this interactivePythonsession:
>>> def f():
... yield 1
... yield 2
... yield 3
...
>>> g = f()
>>> for i in g:
... print i
...
1
2
3
>>> for i in g:
... print i
...
>>> # Note that this time nothing was printed
It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing asC#'s iterator blocksif you're familiar with those.
There's anIBM articlewhich explains it reasonably well (for Python) as far as I can see.
The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values -as if the generator method was paused. Now obviously you can't really "pause" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.
An example in plain language. I will provide a correspondence between high-level human concepts to low-level python concepts.
I want to operate on a sequence of numbers, but I don't want to bother my self with the creation of that sequence, I want only to focus on the operation I want to do. So, I do the following:
I call you and tell you that I want a sequence of numbers which is produced in a specific way, and I let you know what the algorithm is. This step corresponds todefining the generator function, i.e. the function containing ayield.
Sometime later, I tell you, "ok, get ready to tell me the sequence of numbers". This step corresponds to calling the generator function which returns a generator object.Note that you don't tell me any numbers yet, you just grab your paper and pencil.
I ask you, "tell me the next number", and you tell me the first number; after that, you wait for me to ask you for the next number. It's your job to remember where you were, what numbers you have already said, what is the next number. I don't care about the details. This step corresponds to calling.next()on the generator object.
… repeat previous step, until…
eventually, you might come to an end. You don't tell me a number, you just shout, "hold your horses! I'm done! No more numbers!" This step corresponds to the generator object ending its job, and raising aStopIterationexceptionThe generator function does not need to raise the exception, it's raised automatically when the function ends or issues areturn.
This is what a generator does (a function that contains ayield); it starts executing, pauses whenever it does ayield, and when asked for a.next()value it continues from the point it was last. It fits perfectly by design with the iterator protocol of python, which describes how to sequentially request for values.
The most famous user of the iterator protocol is theforcommand in python. So, whenever you do a:
for item in sequence:
it doesn't matter ifsequenceis a list, a string, a dictionary or a generatorobjectlike described above; the result is the same: you read items off a sequence one by one.
Note thatdefining a function which contains ayieldkeyword is not the only way to create a generator; it's just the easiest way to create one.
"it's raised automatically when the function ends or issues areturn"- just notice that in functions containingyieldyou can only havereturnwithout arguments. Trying toreturn somethingthrows SyntaxError.– MestreLionNov 7 '13 at 4:50
There is one type of answer that I don't feel has been given yet, among the many great answers that describe how to use generators. Here is the PL theory answer:
Theyieldstatement in python returns a generator. A generator in python is a function that returnscontinuations(and specifically a type of coroutine, but continuations represent the more general mechanism to understand what is going on).
Continuations in programming languages theory are a much more fundamental kind of computation, but they are not often used because they are extremely hard to reason about and also very difficult to implement. But the idea of what a continuation is, is straightforward: it is the state of a computation that has not yet finished. In this state are saved the current values of variables and the operations that have yet to be performed, and so on. Then at some point later in the program the continuation can be invoked, such that the program's variables are reset to that state and the operations that were saved are carried out.
Continuations, in this more general form, can be implemented in two ways. In thecall/ccway, the program's stack is literally saved and then when the continuation is invoked, the stack is restored.
In continuation passing style (CPS), continuations are just normal functions (only in languages where functions are first class) which the programmer explicitly manages and passes around to subroutines. In this style, program state is represented by closures (and the variables that happen to be encoded in them) rather than variables that reside somewhere on the stack. Functions that manage control flow accept continuation as arguments (in some variations of CPS, functions may accept multiple continuations) and manipulate control flow by invoking them by simply calling them and returning afterwards. A very simple example of continuation passing style is as follows:
In this (very simplistic) example, the programmer saves the operation of actually writing the file into a continuation (which can potentially be a very complex operation with many details to write out), and then passes that continuation (i.e, as a first-class closure) to another operator which does some more processing, and then calls it if necessary. (I use this design pattern a lot in actual GUI programming, either because it saves me lines of code or, more importantly, to wait for GUI events and then execute saved continuations repeatedly)
The rest of this post will, without loss of generality, conceptualize continuations as CPS, because it is a hell of a lot easier to understand and read.
Now let's talk about generators in python. Generators are a specific subtype of continuation. Whereascontinuations are able in general to save the state of acomputation(i.e., the program's call stack),generators are only able to save the state of iteration over aniterator. Although, this definition is slightly misleading for certain use cases of generators. For instance:
def f():
while True:
yield 4
This is clearly a reasonable iterable whose behavior is well defined -- each time the generator iterates over it, it returns 4 (and does so forever). But it isn't probably the prototypical type of iterable that comes to mind when thinking of iterators (i.e.,for x in collection: do_something(x)). This example illustrates the power of generators: if anything is an iterator, a generator can save the state of its iteration.
To reiterate: Continuations can save the state of a program's stack and generators can save the state of iteration. This means that continuations are more a lot powerful than generators, but also that generators are a lot, lot easier. They are easier for the language designer to implement, and they are easier for the programmer to use (if you have some time to burn, try to read and understandthis page about continuations and call/cc).
But you could easily implement (and conceptualize) generators as a simple, specific case of continuation passing style:
Wheneveryieldis called, it tells the function to return a continuation. When the function is called again, it starts from wherever it left off. So, in pseudo-pseudocode (i.e., not pseudocode but not code) the generator'snextmethod is basically as follows:
class Generator():
def __init__(self,iterable,generatorfun):
self.next_continuation = lambda:generatorfun(iterable)
def next(self):
value, next_continuation = self.next_continuation()
self.next_continuation = next_continuation
return value
whereyieldkeyword is actually syntactic sugar for the real generator function, basically something like:
Remember that this is just pseudocode and the actual implementation of generators in python is more complex. But as an exercise to understand what is going on, try to use continuation passing style to implement generator objects without use of theyieldkeyword.
Saying that "generators save the state ofiterables" is somewhat misleading due to terminology. In Python, aniterableis an object that can be converted into an iterator (i.e. has an__iter__or__getitem__methods). When comparing a generator to a continuation, one could say that the generator encapsulates a single execution frame, as opposed to the whole stack, as required by continuation. In that sense, generator is equivalent in power to a coroutine, and post-PEP-342generators are often used in exactly that way.– user4815162342Jul 15 '14 at 5:43
While your objection is technically correct that the example provided is not an iterable as it does not have an__iter__, it can be thought of as a "virtual" iterable whose__iter__simply continues returning items forever. I prefer this way of explaining it, by noting the similarity of this construct with an iterable.– aestrivexJul 18 '14 at 20:45
At this point I no longer understand what you are calling an iterable. A Python iterable is any object whose type implements an__iter__method. This includes generator instances, but also files, and of course every iterator is by definition an iterable because its__iter__returns itself. You could say that a generator saves the state ofiterationover an iterator. Saying that generatorf()"isn't a conventional iterable" makes no sense whatsoever.– user4815162342Jul 18 '14 at 21:39
Instead of say "iterable" -- say "state of iteration over an iterator." That is a good suggestion. I will try to figure out how to work it into this answer.– aestrivexJul 23 '14 at 15:38
I'm completely mislead by your example fib_gen2. Could you elaborate a little 'funky scope due to python2.x workaround for python 3.x use nonlocal' ? I don't grasp the sense of the _ and if there is a reason you use _ and return the function itself, why all that ?– Stephane RollandMay 3 '13 at 11:07
He uses an "anonymous" inner function so that multiple instances of the generator can be instantiated. He takes advantage of the fact that functions, as objects, can be assigned instance variables. In this way, the state of each individual pseudo-generator is stored between invocations. Internally, a generator function works a lot like the third example--you can imagine that Python creates a generator object, and the local variable of the function become the attributes of that object so that they are stored between invocations.– acjayJul 19 '13 at 0:12
While a lot of answers show why you'd use ayieldto create a generator, there are more uses foryield. It's quite easy to make a coroutine, which enables the passing of information between two blocks of code. I won't repeat any of the fine examples that have already been given about usingyieldto create a generator.
To help understand what ayielddoes in the following code, you can use your finger to trace the cycle through any code that has ayield. Every time your finger hits theyield, you have to wait for anextor asendto be entered. When anextis called, you trace through the code until you hit theyield… the code on the right of theyieldis evaluated and returned to the caller… then you wait. Whennextis called again, you perform another loop through the code. However, you'll note that in a coroutine,yieldcan also be used with asend… which will send a value from the callerintothe yielding function. If asendis given, thenyieldreceives the value sent, and spits it out the left hand side… then the trace through the code progresses until you hit theyieldagain (returning the value at the end, as ifnextwas called).
For example:
>>> def coroutine():
... i = -1
... while True:
... i += 1
... val = (yield i)
... print("Received %s" % val)
...
>>> sequence = coroutine()
>>> sequence.next()
0
>>> sequence.next()
Received None
1
>>> sequence.send('hello')
Received hello
2
>>> sequence.close()
This is what I was looking for. Sometimes Stackoverflow is filled with same answers which became noise. Only two people mentioned about coroutine and send.– Kenji NoguchiNov 25 '14 at 0:21
I was going to post "read page 19 of Beazley's 'Python: Essential Reference' for a quick description of generators", but so many others have posted good descriptions already.
Also, note thatyieldcan be used in coroutines as the dual of their use in generator functions. Although it isn't the same use as your code snippet,(yield)can be used as an expression in a function. When a caller sends a value to the method using thesend()method, then the coroutine will execute until the next(yield)statement is encountered.
Generators and coroutines are a cool way to set up data-flow type applications. I thought it would be worthwhile knowing about the other use of theyieldstatement in functions.
A syntax is proposed for a generator to delegate part of its operations to another generator. This allows a section of code containing 'yield' to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.
The new syntax also opens up some opportunities for optimisation when one generator re-yields values produced by another.
I like to think of a thread as having a stack (even if it's not implemented that way).
When a normal function is called, it puts its local variables on the stack, does some computation, returns and clears the stack. The values of its local variables are never seen again.
With ayieldfunction, when it's called first, it similarly adds its local variables to the stack, but then takes its local variables to a special hideaway instead of clearing them, when it returns viayield. A possible place to put them would be somewhere in the heap.
Note that it's notthe functionany more, it's a kind of an imprint or ghost of the function that theforloop is hanging onto.
When it is called again, it retrieves its local variables from its special hideaway and puts them back on the stack and computes, then hides them again in the same way.
def isPrimeNumber(n):
print "isPrimeNumber({}) call".format(n)
if n==1:
return False
for x in range(2,n):
if n % x == 0:
return False
return True
def primes (n=1):
while(True):
print "loop step ---------------- {}".format(n)
if isPrimeNumber(n): yield n
n += 1
for n in primes():
if n> 10:break
print "wiriting result {}".format(n)
I am not an python developer but it looks to me "yield" holds the position of program flow and next time loop start from "yield" position. Seems like waiting at that position and just before that returning value outside and next time continue to work.
To implement thunks (also called anonymous functions), one uses messages sent to a closure object, which has a dispatcher, and the dispatcher answers to "messages".
Prior to beginning tutoring sessions, I ask new students to fill out a brief self-assessment where they rate their understanding of various Python concepts. Some topics ("control flow with if/else" or "defining and using functions") are understood by a majority of students before ever beginning tutoring. There are a handful of topics, however, that almost all students report having no knowledge orverylimited understanding of. Of these, "generatorsand theyieldkeyword" is one of the biggest culprits. I'm guessing this is the case formostnovice Python programmers.
Many report having difficulty understandinggeneratorsand theyieldkeyword even after making a concerted effort to teach themselves the topic. I want to change that. In this post, I'll explainwhattheyieldkeyword does,whyit's useful, andhowto use it.
Note: In recent years, generators have grown more powerful as features have been added through PEPs. In my next post, I'll explore the true power ofyieldwith respect to coroutines, cooperative multitasking and asynchronous I/O (especially their use in the"tulip"prototype implementation GvR has been working on). Before we get there, however, we need a solid understanding of how theyieldkeyword andgeneratorswork.
Coroutines and Subroutines
When we call a normal Python function, execution starts at function's first line and continues until areturnstatement,exception, or the end of the function (which is seen as an implicitreturn None) is encountered. Once a function returns control to its caller, that's it. Any work done by the function and stored in local variables is lost. A new call to the function creates everything from scratch.
This is all very standard when discussing functions (more generally referred to assubroutines) in computer programming. There are times, though, when it's beneficial to have the ability to create a "function" which, instead of simply returning a single value, is able to yield a series of values. To do so, such a function would need to be able to "save its work," so to speak.
I said, "yield a series of values" because our hypothetical function doesn't "return" in the normal sense.returnimplies that the function isreturning control of executionto the point where the function was called. "Yield," however, implies thatthe transfer of control is temporary and voluntary, and our function expects to regain it in the future.
In Python, "functions" with these capabilities are calledgenerators, and they're incredibly useful.generators(and theyieldstatement) were initially introduced to give programmers a more straightforward way to write code responsible for producing a series of values. Previously, creating something like a random number generator required a class or module that both generated values and kept track of state between calls. With the introduction ofgenerators, this became much simpler.
To better understand the problemgeneratorssolve, let's take a look at an example. Throughout the example, keep in mind the core problem being solved:generating a series of values.
Note: Outside of Python, all but the simplestgeneratorswould be referred to ascoroutines. I'll use the latter term later in the post. The important thing to remember is, in Python, everything described here as acoroutineis still agenerator. Python formally defines the termgenerator;coroutineis used in discussion but has no formal definition in the language.
Example: Fun With Prime Numbers
Suppose our boss asks us to write a function that takes alistofints and returns some Iterable containing the elements which are prime1numbers.
Remember, anIterableis just an object capable of returning its members one at a time.
"Simple," we say, and we write the following:
defget_primes(input_list):result_list=list()forelementininput_list:ifis_prime(element):result_list.append()returnresult_list# or better yet...defget_primes(input_list):return(elementforelementininput_listifis_prime(element))# not germane to the example, but here's a possible implementation of# is_prime...defis_prime(number):ifnumber>1:ifnumber==2:returnTrueifnumber%2==0:returnFalseforcurrentinrange(3,int(math.sqrt(number)+1),2):ifnumber%current==0:returnFalsereturnTruereturnFalse
Eitherget_primesimplementation above fulfills the requirements, so we tell our boss we're done. She reports our function works and is exactly what she wanted.
Dealing With Infinite Sequences
Well, not quiteexactly. A few days later, our boss comes back and tells us she's run into a small problem: she wants to use ourget_primesfunction on a very large list of numbers. In fact, the list is so large that merely creating it would consume all of the system's memory. To work around this, she wants to be able to callget_primeswith astartvalue and get all the primes larger thanstart(perhaps she's solvingProject Euler problem 10).
Once we think about this new requirement, it becomes clear that it requires more than a simple change toget_primes. Clearly, we can't return a list of all the prime numbers fromstartto infinity(operating on infinite sequences, though, has a wide range of useful applications). The chances of solving this problem using a normal function seem bleak.
Before we give up, let's determine the core obstacle preventing us from writing a function that satisfies our boss's new requirements. Thinking about it, we arrive at the following:functions only get one chance to return results, and thus must return all results at once.It seems pointless to make such an obvious statement; "functions just work that way," we think. The real value lies in asking, "but what if they didn't?"
Imagine what we could do ifget_primescould simply return thenextvalue instead of all the values at once. It wouldn't need to create a list at all. No list, no memory issues. Since our boss told us she's just iterating over the results, she wouldn't know the difference.
Unfortunately, this doesn't seem possible. Even if we had a magical function that allowed us to iterate fromntoinfinity, we'd get stuck after returning the first value:
defsolve_number_10():# She *is* working on Project Euler #10, I knew it!total=2fornext_primeinget_primes(3):ifnext_prime<2000000:total+=next_primeelse:print(total)return
Clearly, inget_primes, we would immediately hit the case wherenumber = 3and return at line 4. Instead ofreturn, we need a way to generate a value and, when asked for the next one, pick up where we left off.
Functions, though, can't do this. When theyreturn, they're done for good. Even if we could guarantee a function would be called again, we have no way of saying, "OK, now, instead of starting at the first line like we normally do, start up where we left off at line 4." Functions have a singleentry point: the first line.
Enter the Generator
This sort of problem is so common that a new construct was added to Python to solve it: thegenerator. Agenerator"generates" values. Creatinggeneratorswas made as straightforward as possible through the concept ofgenerator functions, introduced simultaneously.
Agenerator functionis defined like a normal function, but whenever it needs to generate a value, it does so with theyieldkeyword rather thanreturn. If the body of adefcontainsyield, the function automatically becomes agenerator function(even if it also contains areturnstatement). There's nothing else we need to do to create one.
generator functionscreategenerator iterators. That's the last time you'll see the termgenerator iterator, though, since they're almost always referred to as "generators". Just remember that ageneratoris a special type ofiterator. To be considered aniterator,generatorsmust define a few methods, one of which is__next__(). To get the next value from agenerator, we use the same built-in function as foriterators:next().
This point bears repeating:to get the next value from agenerator, we use the same built-in function as foriterators:next().
(next()takes care of calling the generator's__next__()method). Since ageneratoris a type ofiterator, it can be used in aforloop.
So whenevernext()is called on agenerator, thegeneratoris responsible for passing back a value to whomever callednext(). It does so by callingyieldalong with the value to be passed back (e.g.yield 7). The easiest way to remember whatyielddoes is to think of it asreturn(plus a little magic) forgenerator functions.**
Again, this bears repeating:yieldis justreturn(plus a little magic) forgenerator functions.
What's the magic part? Glad you asked! When agenerator functioncallsyield, the "state" of thegenerator functionis frozen; the values of all variables are saved and the next line of code to be executed is recorded untilnext()is called again. Once it is, thegenerator functionsimply resumes where it left off. Ifnext()is never called again, the state recorded during theyieldcall is (eventually) discarded.
Let's rewriteget_primesas agenerator function. Notice that we no longer need themagical_infinite_rangefunction. Using a simplewhileloop, we can create our own infinite sequence:
If agenerator functioncallsreturnor reaches the end its definition, aStopIterationexception is raised. This signals to whoever was callingnext()that thegeneratoris exhausted (this is normaliteratorbehavior). It is also the reason thewhile True:loop is present inget_primes. If it weren't, the first timenext()was called we would check if the number is prime and possibly yield it. Ifnext()were called again, we would uselessly add1tonumberand hit the end of thegenerator function(causingStopIterationto be raised). Once a generator has been exhausted, callingnext()on it will result in an error, so you can only consume all the values of ageneratoronce. The following will not work:
>>>our_generator=simple_generator_function()>>>forvalueinour_generator:>>>print(value)>>># our_generator has been exhausted...>>>print(next(our_generator))Traceback(mostrecentcalllast):File"<ipython-input-13-7e48a609051a>",line1,in<module>next(our_generator)StopIteration>>># however, we can always create a new generator>>># by calling the generator function again...>>>new_generator=simple_generator_function()>>>print(next(new_generator))# perfectly valid1
Thus, thewhileloop is there to make sure weneverreach the end ofget_primes. It allows us to generate a value for as long asnext()is called on the generator. This is a common idiom when dealing with infinite series (andgeneratorsin general).
Visualizing the flow
Let's go back to the code that was callingget_primes:solve_number_10.
defsolve_number_10():# She *is* working on Project Euler #10, I knew it!total=2fornext_primeinget_primes(3):ifnext_prime<2000000:total+=next_primeelse:print(total)return
It's helpful to visualize how the first few elements are created when we callget_primesinsolve_number_10'sforloop. When theforloop requests the first value fromget_primes, we enterget_primesas we would in a normal function.
We enter thewhileloop on line 3
Theifcondition holds (3is prime)
We yield the value3and control tosolve_number_10.
Then, back insolve_number_10:
The value3is passed back to theforloop
Theforloop assignsnext_primeto this value
next_primeis added tototal
Theforloop requests the next element fromget_primes
This time, though, instead of enteringget_primesback at the top, we resume at line5, where we left off.
Most importantly,numberstill has the same value it did when we calledyield(i.e.3). Remember,yieldboth passes a value to whoever callednext(),andsaves the "state" of thegenerator function. Clearly, then,numberis incremented to4, we hit the top of thewhileloop, and keep incrementingnumberuntil we hit the next prime number (5). Again weyieldthe value ofnumberto theforloop insolve_number_10. This cycle continues until theforloop stops (at the first prime greater than2,000,000).
Moar Power
InPEP 342, support was added for passing valuesintogenerators.PEP 342gavegenerators the power to yield a value (as before),receivea value, or both yield a valueandreceive a (possibly different) value in a single statement.
To illustrate how values are sent to agenerator, let's return to our prime number example. This time, instead of simply printing every prime number greater thannumber, we'll find the smallest prime number greater than successive powers of a number (i.e. for 10, we want the smallest prime greater than 10, then 100, then 1000, etc.). We start in the same way asget_primes:
defprint_successive_primes(iterations,base=10):# like normal functions, a generator function# can be assigned to a variableprime_generator=get_primes(base)# missing code...forpowerinrange(iterations):# missing code...defget_primes(number):whileTrue:ifis_prime(number):# ... what goes here?
The next line ofget_primestakes a bit of explanation. Whileyield numberwould yield the value ofnumber, a statement of the formother = yield foomeans, "yieldfooand, when a value is sent to me, setotherto that value." You can "send" values to a generator using the generator'ssendmethod.
Two things to note here: First, we're printing the result ofgenerator.send, which is possible becausesendboth sends a value to the generatorandreturns the value yielded by the generator (mirroring howyieldworks from within thegenerator function).
Second, notice theprime_generator.send(None)line. When you're using send to "start" a generator (that is, execute the code from the first line of the generator function up to the firstyieldstatement), you must sendNone. This makes sense, since by definition the generator hasn't gotten to the firstyieldstatement yet, so if we sent a real value there would be nothing to "receive" it. Once the generator is started, we can send values as we do above.
Round-up
In the second half of this series, we'll discuss the various ways in whichgeneratorshave been enhanced and the power they gained as a result.yieldhas become one of the most powerful keywords in Python. Now that we've built a solid understanding of howyieldworks, we have the knowledge necessary to understand some of the more "mind-bending" things thatyieldcan be used for.
Believe it or not, we've barely scratched the surface of the power ofyield. For example, whilesenddoeswork as described above, it's almost never used when generating simple sequences like our example. Below, I've pasted a small demonstration of one common waysendisused. I'll not say any more about it as figuring out how and why it works will be a good warm-up for part two.
importrandomdefget_data():"""Return 3 random integers between 0 and 9"""returnrandom.sample(range(10),3)defconsume():"""Displays a running average across lists of integers sent to it"""running_sum=0data_items_seen=0whileTrue:data=yielddata_items_seen+=len(data)running_sum+=sum(data)print('The running average is {}'.format(running_sum/float(data_items_seen)))defproduce(consumer):"""Produces a set of values and forwards them to the pre-defined consumer function"""whileTrue:data=get_data()print('Produced {}'.format(data))consumer.send(data)yieldif__name__=='__main__':consumer=consume()consumer.send(None)producer=produce(consumer)for_inrange(10):print('Producing...')next(producer)
Remember...
There are a few key ideas I hope you take away from this discussion:
generatorsare used togeneratea series of values
yieldis like thereturnofgenerator functions
The only other thingyielddoes is save the "state" of agenerator function
Ageneratoris just a special type ofiterator
Likeiterators, we can get the next value from ageneratorusingnext()
forgets values by callingnext()implicitly
I hope this post was helpful. If you had never heard ofgenerators, I hope you now understand what they are, why they're useful, and how to use them. If you were somewhat familiar withgenerators, I hope any confusion is now cleared up.
As always, if any section is unclear (or, more importantly, contains errors), by all means let me know. You can leave a comment below, email me atjeff@jeffknupp.com, or hit me up on Twitter@jeffknupp.
Quick refresher: a prime number is a positive integer greater than 1 that has no divisors other than 1 and itself. 3 is prime because there are no numbers that evenly divide it other than 1 and 3 itself. ↩
In this chapter we will learn about iterators, generators and decorators.
Iterators
Python iterator objects required to support two methods while following the iterator protocol.
__iter__returns the iterator object itself. This is used inforandinstatements.
nextmethod returns the next value from the iterator. If there is no more items to return then it should raiseStopIterationexception.
classCounter(object):def__init__(self,low,high):self.current=lowself.high=highdef__iter__(self):'Returns itself as an iterator object'returnselfdefnext(self):'Returns the next value till current is lower than high'ifself.current>self.high:raiseStopIterationelse:self.current+=1returnself.current-1
Remember that an iterator object can be used only once. It means after it raisesStopIterationonce, it will keep raising the same exception.
>>> c = Counter(5,6)
>>> next(c)
5
>>> next(c)
6
>>> next(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in next
StopIteration
>>> next(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in next
StopIteration
Using the iterator in for loop example we saw, the following example tries to show the code behind the scenes.
In this section we learn about Python generators. They were introduced in Python 2.3. It is an easier way to create iterators using a keywordyieldfrom a function.
>>> defmy_generator():... print"Inside my generator"... yield'a'... yield'b'... yield'c'...>>> my_generator()<generator object my_generator at 0x7fbcfa0a6aa0>
In the above example we create a simple generator using the yield statements. We can use it in a for loop just like we use any other iterators.
>>> forcharinmy_generator():... printchar...Inside my generatorabc
In the next example we will create the same Counter class using a generator function and use it in a for loop.
Inside the while loop when it reaches to theyieldstatement, the value of low is returned and the generator state is suspended. During the secondnextcall the generator resumed where it freeze-ed before and then the value oflowis increased by one. It continues with the while loop and comes to theyieldstatement again.
When you call an generator function it returns a *generator* object. If you call *dir* on this object you will find that it contains__iter__and *next* methods among the other methods.
We mostly use generators for laze evaluations. This way generators become a good approach to work with lots of data. If you don’t want to load all the data in the memory, you can use a generator which will pass you each piece of data at a time.
One of the biggest example of such example isos.path.walk()function which uses a callback function and currentos.walkgenerator. Using the generator implementation saves memory.
We can have generators which produces infinite values. The following is a one such example.
If we go back to the example ofmy_generatorwe will find one feature of generators. They are not re-usable.
>>> g=my_generator()>>> forcing:... printc...Inside my generatorabc>>> forcing:... printc...
One way to create a reusable generator is Object based generators which does not hold any state. Any class with a__iter__method which yields data can be used as a object generator. In the following example we will recreate out counter generator.
In this section we will learn about generator expressions which is a high performance, memory efficient generalization of list comprehensions and generators.
For example we will try to sum the squares of all numbers from 1 to 99.
>>> sum([x*xforxinrange(1,10)])
The example actually first creates a list of the square values in memory and then it iterates over it and finally after sum it frees the memory. You can understand the memory usage in case of a big list.
We can save memory usage by using a generator expression.
sum(x*xforxinrange(1,10))
The syntax of generator expression says that always needs to be directly inside a set of parentheses and cannot have a comma on either side. Which basically means both the examples below are valid generator expression usage example.
>>> sum(x*xforxinrange(1,10))285>>> g=(x*xforxinrange(1,10))>>> g<generator object <genexpr> at 0x7fc559516b90>
We can have chaining of generators or generator expressions. In the following example we will read the file */var/log/cron* and will find if any particular job (in the example we are searching for anacron) is running successfully or not.
We can do the same using a shell commandtail -f /var/log/cron |grep anacron
Closures are nothing but functions that are returned by another function. We use closures to remove code duplication. In the following example we create a simple closure for adding numbers.
>>> defadd_number(num):... defadder(number):... 'adder is a closure'... returnnum+number... returnadder...>>> a_10=add_number(10)>>> a_10(21)31>>> a_10(34)44>>> a_5=add_number(5)>>> a_5(3)8
adderis a closure which adds a given number to a pre-defined one.
Decorators
Decorator is way to dynamically add some new behavior to some objects. We achieve the same in Python by using closures.
In the example we will create a simple example which will print some statement before and after the execution of a function.
While you can optimize the heck out of your Python code withgeneratorsandgenerator expressionsI'm more interested in goofing around and solving classic programming questions with theyieldstatement.
note:For this article, since it's easier to explain things as they happen, I'll be including a lot of inline comments.
Let's start with a simple function that returns a sequence of some of my favorite values:
# yielding.pydefpydanny_selected_numbers():# If you multiple 9 by any other number you can easily play with# numbers to get back to 9.# Ex: 2 * 9 = 18. 1 + 8 = 9# Ex: 15 * 9 = 135. 1 + 3 + 5 = 9# See https://en.wikipedia.org/wiki/Digital_rootyield9# A pretty prime.yield31# What's 6 * 7?yield42# The string representation of my first date with Audrey Royyield"2010/02/20"
note:When a function uses theyieldkeyword it's now called agenerator.
Let's do a test drive in the REPL:
>>>fromyieldingimportpydanny_selected_numbers# import ye aulde code>>>pydanny_selected_numbers()# create the iterator object<generatorobjectpydanny_selected_numbersat0x1038a03c0>>>>foriinpydanny_selected_numbers():# iterate through the iterator...print(i)...93142"2010/02/20">>>iterator=pydanny_selected_numbers()# create the iterator object>>>foriiniterator:# iterate through the iterator object...print(i)...93142"2010/02/20"
Of course, if you know anything about generator expressions, you know I could do this more tersely with the following:
While that is more terse, it doesn't give us the amount of control we get by defining our own generator function. For example, what if I want to present the Fibonacci sequence in a loop rather than with recursion?
# fun.pydeffibonacci(max):result=0base=1whileresult<=max:# This yield statement is where the execution leaves the function.yieldresult# This is where the execution comes back into the function. This is# just whitespace, but that it came back while preserving the state# of the function is pretty awesome.# Fibonacci code to increase the number according to# https://en.wikipedia.org/wiki/Fibonacci_numbern=result+baseresult=basebase=nif__name__=="__main__":forxinfibonacci(144):print(x)
What's nice about this is so much more than fibonacci logic in a generator function. Instead, imagine instead of a lightweight calculation I had done something performance intensive. By using generator expressions I can readily control the execution calls with the iterator object'snext()method, saving processor cycles.
Very nifty.
Summary
I admit it. Like many Python developers, I find using tools like yields and generators to optimize the heck out of performance intensive things a lot of fun.
If you are like me and like this sort of stuff, I recommend the following resources:
In the next article I'll demonstrate how to use theyieldstatement to create context managers.
Update:Nicholas Tollerveypointed me at wikipedia's Digital root article, so I added it to the comments of the first code sample.
Update: Oddthinking pointed out that I forgot a print statement. In the REPL it's not really needed, but if this is translated to a script then it's necessary.
Thanks for the discussion and examples on Python "generators" and the "yield" statement.
I just about had it and needed just a little more to get it down. Your discussion and examples here did it.
The Fibonacci sequence with the clear comments was great. I could see clearly that the generator yielded with one value, went out and printed it and then went back into the generator to modify the value before yielding again.
Hi all, I am somewhat new to python - I understood most of it... Very nice! Need a bit of help to understand the following: iterator = (x for x in [9, 31, 42, "2010/02/20"]) Is this a kind of for comprehension? I played with it in REPL - but would like to understand it a little better ;-) Thanks for the lovely article ;-)
You might also have been told aboutrange()which almost lets you write a C-style for loop
foriinrange(len(my_list)):v=my_list[i]printv
17
23
47
51
101
173
999
1001
But neither of the above are natural ways of iterating in python. We do this instead:
forvinmy_list:printv
17
23
47
51
101
173
999
1001
Many types of objects may be iterated over this way. Iterating over strings produces single characters:
forvin"Hello":printv
H
e
l
l
o
Iterating over adictproduces its keys (in no particular order):
d={'a':1,'b':2,'c':3,}forvind:printv# Note the strange order!
a
c
b
Iterating over a file object produces lines from that file, including the line termination:
f=open("suzuki.txt")forlineinf:print">",line
> On education
> "Education has failed in a very serious way to convey the most important lesson science can teach: skepticism."
> "An educational system isn't worth a great deal if it teaches young people how to make a living but doesn't teach them how to make a life."
Objects that can be iterated over in python are called "Iterables", and a for loop isn't the only thing that accepts iterables.
The list constructor takes any iterable. We can use this to make a list of the keys in adict:
list(d)
['a', 'c', 'b']
Or the characters in a string:
list("Hello")
['H', 'e', 'l', 'l', 'o']
List comprehensions take iterables.
ascii=[ord(x)forxin"Hello"]ascii
[72, 101, 108, 108, 111]
Thesum()function takes any iterable that produces numbers.
sum(ascii)
500
Thestr.join()method takes any iterable that produces strings.
"-".join(d)
'a-c-b'
Iterables can produce any python object. There.finditer()function returns an iterable that producesre.matchobjects.
Luckyis a class that will return7for any index less than or equal to3:
lucky=Lucky()lucky[0]
7
And raise anIndexErrorfor larger indexes:
lucky[6]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/home/ian/git/iterables-iterators-generators/<ipython-input-15-5c0a87559915> in <module>()
----> 1 lucky[6]
/home/ian/git/iterables-iterators-generators/<ipython-input-13-bd578dbfbead> in __getitem__(self, index)
2 def __getitem__(self, index):
3 if index > 3:
----> 4 raise IndexError
5 return 7
IndexError:
This is a perfectly well-behaved python iterable. We can loop over it:
fornumberinlucky:printnumber
7
7
7
7
Or pass it to functions that take iterables:
list(lucky)
[7, 7, 7, 7]
Even theinoperator works with it:
7inlucky
True
But writing this sort of class it difficult. You need to be able to return a value for any index passed to__getitem__()but most of the time you really only want to produce items in order from first to last.
The naming is confusingly similar here, but it's important to understand the difference betweeniterablesanditerators.
Iterators are iterables with some kind of 'position' state and a.next()method. The.next()method may be called to produce the next item and update the internal state.
Iterables are objects that produce an iterator when they are passed to theiter()builtin.
Callingiter()on our "classic" iterable object produces a plainiteratorinstance
i=iter(lucky)i
<iterator at 0x288cc10>
This plainiteratorhas a counter and the original object as its internal state. Calling.next()advances the counter and calls our "classic" iterable's.__getitem__()method.
When we get to the end however, ourIndexErrorexception is turned into aStopIterationexception. This is the iterator protocol: when.next()raisesStopIterationthere are no more items to be produced.
Remember that an iteratorisan iterable, so it can be passed to anything that takes an iterable.
Be careful, though. Iterators may only be iterated over once, since they are updating their internal state as they go. If we try to iterate twice, the second time will produce no more items:
i=iter(lucky)printlist(i)printlist(i)
[7, 7, 7, 7]
[]
Calling oniter()on an iterable will produce a different iterator object each time.
iisiter(lucky)
False
Also, like other iterables, callingiter()on an iterator works, but it behaves differently!
Callingiter()on an iterator typically returns the exact same iterator. If you think about it, that's all that can be done because you can't rewind or duplicate an iterator in the general case.
iisiter(i)
True
Iterators come in all shapes and sizes.
xrange()has arangeiterator:
iter(xrange(20))
<rangeiterator at 0x2896900>
dicthas adictionary-keyiterator:
iter({'a':1,'b':2})
<dictionary-keyiterator at 0x2894aa0>
listdoesn't even use the plainiteratortype, and instead uses its own more efficientlistiterator:
iter([4,5,6])
<listiterator at 0x28973d0>
And some have names that provide no clue what they iterate over:
Our internal 'position' state is a list of items we pop one at a time when.next()is called. We implement.__iter__()in the normal way for an iterator:"return self". We raiseStopIterationwhen we have nothing left to produce.
This works as expected, but it's rather a lot of code for a simple result.
A generator function is a simpler way to create an iterator.
Generator functions let you use local variables and the position of the program counter as state for a generator object. A new generator object is created and returned each time you call a generator function. The generator object is an iterator.
Here is a generator function thatonlyuses the program counter for state:
When we call the generator function it does nothing except create a new generator object. None of the code in the generator function has been executed yet.
countdown_generator()
<generator object countdown_generator at 0x289d0f0>
As the generator object is iterated over execution starts, following the generator function definition until the nextyieldstatement.
When it reaches theyieldstatement execution is paused (the program counter is stored) and the value on the right of theyieldstatement is produced as a value from the generator object. Execution is resumed from the stored program counter position when iteration continues.
When the generator function reaches the end, the generator raises aStopIterationexception just like a normal iterator. And it behaves just like a normal iterator:
fornincountdown_generator():printn
5
4
3
2
1
launch
Now we have a much more concise way of defining our own iterator for an iterable class. The.__iter__()method of our class can be written as a generator function:
But, enough about classes. Let's dig further into how these generators work.
Recall that execution of the code in a generator function does not proceed until the generator object returned is iterated over. That lets us put things in a generator that might be expensive, knowing that we will only have to pay that cost when we actually ask it to produce the next item.
This generator causes a for loop to slow down between iterations. First waiting 5 seconds, then counting down from "5" to "1" with 1 seconds intervals in between:
Another way of writing this code is to turn the generator inside-out.
Instead of sleeping inside the generator we canyieldthe amount of time we want to sleep. And instead ofyield-ing the countdown we can use a function passed in to display values to the user.
Ashow()function takes the place of the print inside the loop, and thetime.sleep()call is done by the code iterating over the generator. This puts the code driving the generator in charge of how (or if) it sleeps for the given time.
While a generator object is an iterator, it can also be used for much more.
When paused at ayieldstatement generator objects can receive data by using.send()instead of.next().
When we useyieldas an expression or assign it to a variable, the value passed to.send()is available inside the generator.
defknock_knock():name=yield"Who's there?"yield"%s who?"%nameyield"That's not funny at all"
We have to switch to manually calling.next()on our generator object, because aforloop or function that takes an iterable won't be able to call.send()when we need to.
k=knock_knock()k.next()
"Who's there?"
At this point execution is paused at the firstyield. The assignment to the variablenamehasn't happened yet. But when we.send()a value execution continues:
k.send("David")
'David who?'
And in the generator object we are at the secondyieldwith"David"assigned toname.
If we send something to ayieldthat isn't being used as an expression, the value we send will be ignored:
k.send("David the environmentalist")
"That's not funny at all"
But execution continues the same as if we called.next().
This is the end of part 1.
Inpart 2we build a simple interactive network game with 90% of the code written as generators. I will show how breaking down asynchronous code into generators can make it easy to test, easy to reuse, and (with some practice) easy to understand.
Les générateurs sont une fonctionalité fabuleuse de Python, et une étape indispensable dans la maîtrise du langage. Une fois compris,vous ne pourrez plus vous en passer.
Rappel sur les itérables
Quand vous lisez des éléments un par un d’une liste, on appelle cela l’itération:
lst =[1,2,3]>>>for i in lst :
... print(i)123
Et quand on utilise une liste en intention, on créé une liste, donc un itérable. Encore une fois, avec une bouclefor, on prend ses éléments un par un, donc onitèredessus:
lst =[x*x for x inrange(3)]>>>for i in lst :
... print(i)014
À chaque fois qu’on peut utiliser “for…in…” sur quelque chose, c’est un itérable : lists, strings, files…
Ces itérables sont pratiques car on peut les lire autant qu’on veut, mais ce n’est pas toujours idéal car on doit stocker tous les éléments en mémoire.
Les générateurs
Si vous vous souvenez de l’article surles comprehension lists, on peut également créer des expressions génératrices:
generateur =(x*x for x inrange(3))>>>for i in generateur :
... print(i)014
La seule différence avec précédemment, c’est qu’on utilise()au lieu de[]. Mais on ne peut pas liregenerateurune seconde fois car le principe des générateurs, c’est justement qu’ils génèrent tout à la volée: ici il calcule0, puis l’oublie, puis calcule1, et l’oublie, et calcule4. Tout ça un par un.
Le mot clé yield
yieldest un mot clé utilisé en lieu et place dereturn, à la différence prêt qu’on va récupérer un générateur.
>>>def creerGenerateur() :
... mylist=range(3)
... for i in mylist:
... yield i*i
...
>>> generateur = creerGenerateur()# crée un générateur>>>print(generateur)# generateur est un objet !< generator object creerGenerateur at 0x2b484b9addc0>>>>for i in generateur:
... print(i)014
Ici c’est un exemple inutile, mais dans la vraie vie vivante, c’est pratique quand on sait que la fonction va retourner de nombreuses valeurs qu’on ne souhaite lire qu’une seule fois.
Le secret des maîtres Zen qui ont acquis la compréhension transcendantale deyield, c’est de savoir quequand on appelle la fonction, le code de la fonction n’est pas exécute. A la place, la fonction va retourner un objet générateur.
C’est pas évident à comprendre, alors relisez plusieurs fois cette partie.
creerGenerateur()n’exécute pas le code decreerGenerateur.
creerGenerateur()retourne un objet générateur.
En fait,tant qu’on ne touche pas au générateur, il ne se passe rien. Puis,dès qu’on commence à itérer sur le générateur, le code de la fonction s’exécute.
La première fois que le code s’éxécute, il va partir du début de la fonction, arriver jusqu’àyield, et retourner la première valeur. Ensuite, à chaque nouveau tour de boucle, le code va reprendre de la où il s’est arrêté (oui, Python sauvegarde l’état du code du générateur entre chaque appel), et exécuter le code à nouveau jusqu’à ce qu’il rencontreyield. Donc dans notre cas, il va faire un tour de boucle.
Il va continuer comme ça jusqu’à ce que le code ne rencontre plusyield, et donc qu’il n’y a plus de valeur à retourner. Le générateur est alors considéré comme définitivement vide. Il ne peut pas être “rembobiné”, il faut en créer un autre.
La raison pour laquelle le code ne rencontre plus yield est celle de votre choix: conditionif/else, boucle, recursion… Vous pouvez même yielder à l’infini.
Un exemple concret et un café, plz
yieldpermet non seulement d’économiser de la mémoire, mais surtout de masquer la complexité d’un algo derrière une API classique d’itération.
Supposez que vous ayez une fonction qui – tada ! – extrait les mots de plus de 3 caractères de tous les fichiers d’un dossier.
Elle pourrait ressembler à ça:
importosdef extraire_mots(dossier):
for fichier inos.listdir(dossier):
withopen(os.path.join(dossier, fichier))as f:
for ligne in f:
for mot in ligne.split():
iflen(mot)>3:
yield mot
Vous avez là un algo dont on masque complètement la complexité, car du point de vue de l’utilisateur, il fait juste ça:
for mot in extraire_mots(dossier):
print mot
Et pour lui c’est transparent. En plus, il peut utiliser tous les outils qu’on utilise sur les itérables d’habitude. Toutes les fonctions qui acceptent les itérables acceptent donc le résultat de la fonction en paramètre grâce à la magie du duck typing. On créé ainsi une merveilleuse toolbox.
Allumer une machine vide n’a jamais permis de remplir le stock ;-) Mais il suffit de remplir le stock pour repartir comme en 40:
>>> distributeur_en_bas_de_la_rue.stock=True>>> distribuer = distributeur_en_bas_de_la_rue.allumer()>>>for c in distribuer :
... print c
capote
capote
capote
capote
capote
capote
capote
capote
capote
capote
capote
capote
...
itertools: votre nouveau module favori
Le truc avec les générateurs, c’est qu’il faut les manipuler en prenant en compte leur nature: on ne peut les lire qu’une fois, et on ne peut pas déterminer leur longeur à l’avance.itertoolsest un module spécialisé la dedans:map,zip,slice… Il contient des fonctions qui marchent sur tous les itérables, y compris les générateurs.
Et rappelez-vous, les strings, les listes, les sets et même les fichiers sont itérables.
Chaîner deux itérables, et prendre les 10 premiers caractères ? Piece of cake !
>>>importitertools>>> d = DistributeurDeCapote().allumer()>>> generateur =itertools.chain("12345", d)>>> generateur =itertools.islice(generateur,0,10)>>>for x in generateur:
... print x
...
12345
capote
capote
capote
capote
capote
Les dessous de l’itération
Sous le capôt, tous les itérables utilisent un générateur appelé “itérateur”. On peut récupérer l’itérateur en utiliser la fonctioniter()sur un itérable:
>>>iter([1,2,3])< listiterator object at 0x7f58b9735dd0>>>>iter((1,2,3))< tupleiterator object at 0x7f58b9735e10>>>>iter(x*x for x in(1,2,3))< generator object at 0x7f58b9723820>
Les itérateurs ont une méthode next() qui retourne une valeur pour chaque appel de la méthode. Quand il n’y a plus de valeur, ils lèvent l’exceptionStopIteration:
>>> gen =iter([1,2,3])>>> gen.next()1>>> gen.next()2>>> gen.next()3>>> gen.next()
Traceback (most recent call last):
File "< stdin>", line 1,in< module>StopIteration
Message à tous ceux qui pensent que je fabule quand je dis qu’en Python on utilise les exceptions pour contrôler le flux d’un programme (sacrilège !): ceci est le mécanisme des boucles interne en Python. Les bouclesforutilisentiter()pour créer un générateur, puis attrappent une exception pour s’arrêter.À chaque bouclefor, vous levez une exception sans le savoir.
Pour la petite histoire, l’implémentation actuelle est queiter()appelle la méthode__iter__()sur l’objet passé en paramètre. Donc ça veut dire que vous pouvez créer vos propres itérables:
>>>class MonIterableRienQuaMoi(object):
... def__iter__(self):
... yield'Python'
... yield"ça"
... yield'déchire'
...
>>> gen =iter(MonIterableRienQuaMoi())>>> gen.next()'Python'>>> gen.next()'ça'>>> gen.next()'déchire'>>> gen.next()
Traceback (most recent call last):
File "< stdin>", line 1,in< module>StopIteration>>>for x in MonIterableRienQuaMoi():
... print x
...
Python
ça
déchire
12 thoughts on “Comment utiliseryieldet les générateurs en Python ?”
Poulet 2.0
Petit typo dans l’exemple concret (merci pour le café):
for mot in ligne.s<strong>p</strong>lit():
Luigi
Super bien expliqué !
SamPost author
:-)
Merci à tous les deux.
(la flemme de mettre un tampon…)
Titus Crow
Petite coquille également : for mot in extraire_mots(dossier):
(pour les gens qui reprennent vos exemples en copié-collé ^^’)
Feadurn
Un tout tout grand merci pour ce blog, apprenant python sur le tas pour les necessite de ma recherche, je peux enfin arriver a faire des choses un peu plus complexe grace a vous. La par exemple je suis dans le tuto sur les classes, et je vais peut etre enfin arriver a comprendre la POO.
Pour que ce message soit un tantinet utile, dans la phrase
“creerGenerateur() n’éxécute pas le code de creerGenerateur.creerGenerateur() retourne un objet générateur.” il manque peut etre un “mais” (ok c’etait pas si utile que ca finalement)
SamPost author
Effectivement y a moyen de rendre ça plus clair. J’ai fais un édit :-)
Krikor
Si j’ai bien compris, l’intérêt de yield est de ne pas stocker en mémoire une grosse liste d’élément pour s’en servir mais d’aller chercher l’info dont on a besoin, s’en servir et tout de suite l’éliminer de la mémoire ? J’espère que je ne dis pas de bêtises, c’est juste pour bien comprendre quand utiliser yield plutôt que de retourner une liste.
SamPost author
Tout à fait. Yield permet aussi d’applanir des algorithmes complexes pour les exposer comme le parcours d’une liste.
policier moustachu
Yo ! Je me suis fais un petit algo récursif pour calculer toutes les combinaisons de n entiers dont la somme fait m. Et pour pas exploser la pile je me demandais si c’était possible d’utiliser yield. Mais c’est pas évident évident …
def pilepoile(n, taille): if taille == 1: return [[n]] else: toutes_les_listes = [] for i in range(n + 1): intermediates = pilepoile(n-i, taille -1) for l in intermediates: l.insert(0,i) toutes_les_listes.extend(intermediates) return toutes_les_listes
policier moustachu
def pilepoile(n, taille): if taille == 1: return [[n]] else: toutes_les_listes = [] for i in range(n + 1): intermediates = pilepoile(n-i, taille -1) for l in intermediates: l.insert(0,i) toutes_les_listes.extend(intermediates) return toutes_les_listes
policier moustachu
Désolé j’arrive pas à utiliser les tags de code proprement tamponnez moi fort.
GUILLAUME LE GALL
Très bonne explication qui permet d’apréhender les subtilités des générateurs !
Leave a comment
Des questions Python sans rapport avec l'article ? Posez-les surIndexError.
Petit typo dans l’exemple concret (merci pour le café):
Super bien expliqué !
:-)
Merci à tous les deux.
(la flemme de mettre un tampon…)
Petite coquille également :
for mot in extraire_mots(dossier):
(pour les gens qui reprennent vos exemples en copié-collé ^^’)
Un tout tout grand merci pour ce blog, apprenant python sur le tas pour les necessite de ma recherche, je peux enfin arriver a faire des choses un peu plus complexe grace a vous. La par exemple je suis dans le tuto sur les classes, et je vais peut etre enfin arriver a comprendre la POO.
Pour que ce message soit un tantinet utile, dans la phrase
“creerGenerateur() n’éxécute pas le code de creerGenerateur.creerGenerateur() retourne un objet générateur.” il manque peut etre un “mais” (ok c’etait pas si utile que ca finalement)
Effectivement y a moyen de rendre ça plus clair. J’ai fais un édit :-)
Si j’ai bien compris, l’intérêt de yield est de ne pas stocker en mémoire une grosse liste d’élément pour s’en servir mais d’aller chercher l’info dont on a besoin, s’en servir et tout de suite l’éliminer de la mémoire ?
J’espère que je ne dis pas de bêtises, c’est juste pour bien comprendre quand utiliser yield plutôt que de retourner une liste.
Tout à fait. Yield permet aussi d’applanir des algorithmes complexes pour les exposer comme le parcours d’une liste.
Yo ! Je me suis fais un petit algo récursif pour calculer toutes les combinaisons de n entiers dont la somme fait m.
Et pour pas exploser la pile je me demandais si c’était possible d’utiliser yield. Mais c’est pas évident évident …
def pilepoile(n, taille):
if taille == 1:
return [[n]]
else:
toutes_les_listes = []
for i in range(n + 1):
intermediates = pilepoile(n-i, taille -1)
for l in intermediates:
l.insert(0,i)
toutes_les_listes.extend(intermediates)
return toutes_les_listes
def pilepoile(n, taille):
if taille == 1:
return [[n]]
else:
toutes_les_listes = []
for i in range(n + 1):
intermediates = pilepoile(n-i, taille -1)
for l in intermediates:
l.insert(0,i)
toutes_les_listes.extend(intermediates)
return toutes_les_listes
Désolé j’arrive pas à utiliser les tags de code proprement tamponnez moi fort.
Très bonne explication qui permet d’apréhender les subtilités des générateurs !