Python equivalent of Common Lisp Macros?
dpapathanasiou
denis.papathanasiou at gmail.com
Wed Nov 26 15:26:40 EST 2008
On Nov 26, 2:30 pm, "Chris Rebert" <c... at rebertia.com> wrote:
> On Wed, Nov 26, 2008 at 11:13 AM, dpapathanasiou
>
> <denis.papathanas... at gmail.com> 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)
Thanks; this is exactly what I was looking for.
More information about the Python-list
mailing list