Today we’ll see how to use the throw method on generators.
If you haven’t read my previous two articles on generators (about the basics of generators and sending objects to generators), it’s definitely recommended to do so before you go on with this one.
And now let’s have a look at the code from my previous article again:
>>> def letter_generator(text):
... position = 0
... while True:
... message = yield text[position]
... if message!= None:
... position = message
... else:
... position += 1
This generator yields the letters making up text. Suppose, we need to know the value of position as well. The generator object can use the throw method to get this information.
How does the throw method work? It raises an exception at the point where the generator’s execution was stopped and returns the next value yielded by the generator or, if the generator doesn’t yield any value, it raises the StopIteration exception. The exception passed as an argument to throw must be handled in the generator function or else it will propagate to the caller. Now let’s rewrite the code above so that it can handle the exception and so that the value of position is available. The generator is now saved in a file called generators.py. We use the try and except keywords to handle exceptions:
def letter_generator(text):
position = 0
while True:
try:
message = yield text[position]
except Exception:
print("position = " + str(position))
if message!= None:
position = message
else:
position += 1
Now let’s work in interactive mode. Let’s import the generator we need:
>>> from generators import letter_generator
Now let’s create the generator object:
>>> letters = letter_generator("abcdefghijklmnopqrstucwxyz")
The iterator is ready to work:
>>> next(letters)
'a'
>>> next(letters)
'b'
Now let’s use the throw method on the iterator. This way we’ll be informed about the current value of position. Also, the next element will be returned:
>>> letters.throw(Exception)
position = 1
'c'
Let’s use next again:
>>> next(letters)
'd'
And finally let’s use throw again. Now the value of position is different:
>>> letters.throw(Exception)
position = 3
'e'
Here’s the video version of the article: