Main Content

Good example of recursion in Python - analyse an RSS feed

Archive - Originally posted on "The Horse's Mouth" - 2009-11-18 18:19:13 - Graham Ellis

I'm not keen on recursive code - code that calls itself. Very often, such code is elegant in a way, yet so 'clever' that it is hard to follow. There are, however, exceptions where I say "THAT is a good use of recursion". Once such is in the handling / parsing of RSS (Really Simple Syndication) feeds.

I was asked by one of my delegates about how he might download and analyse an RSS feed in Python ... and after a quick scout around, we downloaded feedparser. The code to grab the feed is silly-trivial:

import feedparser
stuff = feedparser.parse("http://www.wellho.net/horse/index.xml")


stuff, though, is a dictionary that contains other dictionaries, lists, and strings ... and those other dictionaries and strings contain further dictionaries and strings and lists. After all, RSS is an XML feed and the parse method give you back something synonymous with a DOM object.

So I have "pretty print"ed stuff using a function I wrote called display_dict which itself calls display_dict and display_list as appropriate. display_list itself calls display_list and display_dict. You can see the source at [link]