OT: Crazy Programming

Andrew Dalke dalke at dalkescientific.com
Mon May 13 12:55:52 EDT 2002


Max M:
># Best practice (519 chars)
>def listView(listOfObjects):
>     result = []
>     a = result.append
>     for object in listOfObjects:
>         if object.objectType in ['folder', 'content holder']:
>             a('<img src="folder.gif">')
>         else:
>             a('<img src="content.gif">')
>         a('%s<br>' % object.title)
>         a('<font size="-1"><b>%s</b></font>' % object.summary)
>         a('[<a href="view.asp?id=%s">View</a>]' % object.id)
>         a('[<a href="edit.asp?id=%s">Edit</a>]<br>' % object.id)
>     return ''.join(result)

Why is this 'best practice'?  At the very least, I would have used
"append = result.append" because "a" can be confused (in an HTML context)
for the request to do an "a" tag.

Have you considered this alternative?

import cgi, urllib
class ListViewAdapter:
  funcs = {"quote": urllib.quote,
           "escape": cgi.escape,
           "str": str}
  img = {"folder": "folder.gif",
         "content holder": "folder.gif"}
  def __init__(self, obj):
    self.obj = obj
  def __getitem__(self, item):
    terms = item.split("|")
    name, terms = terms[0], terms[1:]
    if name == "gifimage":
      s = self.img.get(self.obj.objectType, "content.gif")
    else:
      s = getattr(self.obj, name)
    for term in terms:
      s = self.funcs[term](s)
    return s

def listView(listOfObjects):
     template = """\
<img src="%(gifimage)s">%(title|escape)s<br>
<font size="-1"><b>%(summary|escape)s</b></font>
[<a href="view.asp?id=?%(id|quote)s">View</a>]
[<a href="edit.asp?id=%(id|quote)s">Edit</a>]<br>
"""
     return "".join([ template % ListViewAdapter(obj)
                               for obj in listOfObjects ])

It's a bit more complicated than yours partially because
you don't have the code for escaping special characters
inside of HTML text and or quoting characters inside
of HTML tags.

What it does is leverage Python's string interpolation
to get the attribute you want to use, and optionally apply
any set of transformations you want done on that value.  The
result makes it much easier to see how the HTML looks
in one go rather than building it up through many
Python commands.

                        Andrew
                        dalke at dalkescientific.com






More information about the Python-list mailing list