Need advice on how to improve this function

Matthew Wilson matt at tplus1.com
Sun Aug 20 10:05:13 EDT 2006


I wrote a function that converts a tuple of tuples into html.  For
example:

    In [9]: x
    Out[9]:
    ('html',
     ('head', ('title', 'this is the title!')),
     ('body',
      ('h1', 'this is the header!'),
      ('p', 'paragraph one is boring.'),
      ('p',
       'but paragraph 2 ',
       ('a', {'href': 'http://example.com'}, 'has a link'),
       '!')))


    In [10]: as_html(x, sys.stdout)
    <html>

    <head>

    <title>this is the title!</title>

    </head>

    <body>

    <h1>this is the header!</h1>

    <p>paragraph one is boring.</p>

    <p>but paragraph 2 <a href="http://example.com">has a link</a>!</p>

    </body>

    </html>


I'd like to know ways to make it better (more efficient, able to deal
with enormous-size arguments, etc).  How would I write this as a
generator?

Here's the definition for as_html:

def as_html(l, s):
    "Convert a list or tuple into html and write it to stream s."
    if isinstance(l, (tuple, list)):
        tagname = l[0]
        if isinstance(l[1], dict):
            attributes = ' '.join(['%s="%s"' % (k, l[1][k]) for k in l[1]])
            s.write('<%s %s>' % (tagname, attributes))
        else:
            s.write('<%s>' % tagname)
        if tagname in ('html', 'head', 'body'):
            s.write('\n\n')
        for ll in l[1:]:
            as_html(ll, s)
        s.write('</%s>' % tagname)
        if tagname not in ('a', 'b', 'ul'):
            s.write('\n\n')
    elif isinstance(l, str):
        s.write(l)


All comments welcome. TIA

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles



More information about the Python-list mailing list