On Wed, Nov 26, 2008 at 11:13 AM, dpapathanasiou <[EMAIL PROTECTED]> wrote: > I'm using the feedparser library to extract data from rss feed items. > > After I wrote this function, which returns a list of item titles, I > noticed that most item attributes would be retrieved the same way, > i.e., the function would look exactly the same, except for the single > data.append line inside the for loop. > > In CL, I could simply write a macro, then replace the data.append line > depending on which attribute I wanted. > > Is there anything similar in Python?
Yes, use higher-order functions. See below. > > Here's the function: > > def item_titles (feed_url): Replace previous line with: def item_titles(feed_url, attr_getter): > """Return a list of the item titles found in this feed url""" > data = [] > feed = feedparser.parse(feed_url) > if feed: > if len(feed.version) > 0: > for e in feed.entries: > data.append(e.title.encode('utf-8')) Replace previous line with: data.append(attr_getter(e)) > return data Example usage: def title_getter(entry): return entry.title.encode('utf-8') titles = item_titles("some feed url here", title_getter) As I'm not familiar with feedparser, you might want to move where the .encode() takes place, but you get the idea. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list