Iterators and Exceptions

January 26, 2009

Here’s the situation. I have a list of symbol objects, and each object has an associated test method. The test method accepts a piece of a time series and asks whether or not the symbol associated with that object can represent this piece of a time series. If the symbol can represent that piece of time series, the test returns True, otherwise False.

Now say I have 100 different symbols in a list called symbols – how do I find which symbol corresponds to a particular piece of a time series? Simple: I check each one and stop checking once I’ve found the correct symbol. Here’s a little idiom to do that:

symbol_iter = iter(symbols)
still_looking = True
try:
	while still_looking:
		symbol = symbol_iter.next()
		if symbol.test(timeseries):
			name = symbol.name
			still_looking = False
except StopIteration: 
	raise ValueError("didn't find an appropriate symbol")

So I take my list of symbols and turn it into an iterator using iter(). This means that when I call next() as a method of the iterator, it will give me the next value in the list, or it will raise a StopIteration exception. So all I need to do is keep calling the next() method until I find the symbol. When I find it I do whatever I want to do (in this case store the name of the symbol) and halt the while loop. If for whatever reason it reaches the end of the list of symbols without having found the appropriate symbol it will throw a StopIteration which I catch and turn into a ValueError.

For a list of all the built-in exceptions see here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: