Python equivalent of Common Lisp Macros?
Diez B. Roggisch
deets at nospam.web.de
Wed Nov 26 14:26:50 EST 2008
dpapathanasiou schrieb:
> 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?
>
> Here's the function:
>
> def item_titles (feed_url):
> """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'))
> return data
No, there are no macros. Yet it has - amongst other options, such as
callbacks - decorators, that would allow you to write your code like this:
def items (feed_url):
feed = feedparser.parse(feed_url)
if feed:
if len(feed.version) > 0:
for e in feed.entries:
yield e
titles = []
other_things = []
for item in items(url):
titles.append(item.title.encode('utf-8'))
other_things.append(item.other_thing)
Diez
More information about the Python-list
mailing list