syntax from diveintopython

Mark Pilgrim f8dy at yahoo.com
Tue Apr 17 15:45:00 EDT 2001


"Fredrik Lundh" <fredrik at pythonware.com> wrote in message
news:nc%C6.5081$sk3.1501293 at newsb.telia.net...
> > def unknown_starttag(self, tag, attrs):
> >    strattrs = "".join([' %(key)s="%(value)s"' % locals() for key, value
in attrs])
> >    self.parts.append("<%(tag)s%(strattrs)s>" % locals())
>
> whoever wrote the original code should have their python license
> revoked.

Well, you wouldn't be the first person to tell me that. <0.5 wink>

For those not familiar with how SGMLParser works, it will call this method
with an HTML tag ("tag", a string) and the attributes of the tag ("attrs", a
list of (key,value) tuples).  This code reconstructs the original tag and
appends it to the list self.parts.

- Suppose the original tag is '<a href="index.html" title="Go to home
page">'
- The method will be called with tag='a' and attrs=[('href', 'index.html'),
('title', 'Go to home page')]
- The list comprehension will produce a list of 2 elements: ['
href="index.html"', ' title="Go to home page"']
- strattrs will be ' href="index.html" title="Go to home page"'
- The string appended to self.parts will be '<a href="index.html" title="Go
to home page">', which is what we want.

Other than using string.join(..., "") instead of "".join(...) -- a topic
which has been beaten to death recently on this newsgroup and which I
address explicitly in my book
(http://diveintopython.org/odbchelper_join.html) -- how would you rewrite
this?

-M
You're smart; why haven't you learned Python yet?
http://diveintopython.org/
Now in Chinese!  http://diveintopython.org/cn/






More information about the Python-list mailing list