syntax from diveintopython

Fredrik Lundh fredrik at pythonware.com
Tue Apr 17 16:53:44 EDT 2001


Mark Pilgrim wrote:
> 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?

if you write it in a more straightforward way, it runs about twice
as fast (using a test case with one attribute per tag, on average):

    def unknown_starttag(self, tag, attrs):
        self.parts.append("<" + tag)
        for kv in attrs:
            self.parts.append(" %s='%s'" % kv)
        self.parts.append(">")

you can save some extra cycles by binding the append
method to a local slot:

    def unknown_starttag(self, tag, attrs):
        append = self.parts.append
        append("<" + tag)
        for kv in attrs:
            append(" %s='%s'" % kv)
        append(">")

but it's still buggy: if an attribute value contains a reserved
character (a character entity), it will produce bogus output.
this variant works better:

    def unknown_starttag(self, tag, attrs):
        append = self.parts.append
        append("<" + tag)
        for k, v in attrs:
            append(" %s='%s'" % (k, cgi.escape(v)))
        append(">")

Cheers /F

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->






More information about the Python-list mailing list