You are here: Home > Dive Into Python > HTML Processing > Dictionary-based string formatting | << >> | ||||
Dive Into PythonPython from novice to pro |
Why did you learn about locals and globals? So you can learn about dictionary-based string formatting. As you recall, regular string formatting provides an easy way to insert values into strings. Values are listed in a tuple and inserted in order into the string in place of each formatting marker. While this is efficient, it is not always the easiest code to read, especially when multiple values are being inserted. You can't simply scan through the string in one pass and understand what the result will be; you're constantly switching between reading the string and reading the tuple of values.
There is an alternative form of string formatting that uses dictionaries instead of tuples of values.
Example 8.13. Introducing dictionary-based string formatting
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> "%(pwd)s" % params 'secret' >>> "%(pwd)s is not a good password for %(uid)s" % params 'secret is not a good password for sa' >>> "%(database)s of mind, %(database)s of body" % params 'master of mind, master of body'
So why would you use dictionary-based string formatting? Well, it does seem like overkill to set up a dictionary of keys and values simply to do string formatting in the next line; it's really most useful when you happen to have a dictionary of meaningful keys and values already. Like locals.
Example 8.14. Dictionary-based string formatting in BaseHTMLProcessor.py
def handle_comment(self, text): self.pieces.append("<!--%(text)s-->" % locals())
Example 8.15. More dictionary-based string formatting
def unknown_starttag(self, tag, attrs): strattrs = "".join([' %s="%s"' % (key, value) for key, value in attrs]) self.pieces.append("<%(tag)s%(strattrs)s>" % locals())
When this method is called, attrs is a list of key/value tuples, just like the items of a dictionary, which means you can use multi-variable assignment to iterate through it. This should be a familiar pattern by now, but there's a lot going on here, so let's break it down:
|
|
Now, using dictionary-based string formatting, you insert the value of tag and strattrs into a string. So if tag is 'a', the final result would be '<a href="index.html" title="Go to home page">', and that is what gets appended to self.pieces. |
Using dictionary-based string formatting with locals is a convenient way of making complex string formatting expressions more readable, but it comes with a price. There is a slight performance hit in making the call to locals, since locals builds a copy of the local namespace. |
<< locals and globals |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
Quoting attribute values >> |