04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 10 ■ BATTERIES INCLUDED 247<br />

Making a template system. A template is a file you can put specific values into to get a finished text of some kind.<br />

For example, you may have a mail template requiring only the insertion of a recipient name. Python already has an<br />

advanced template mechanism: string formatting. However, with regular expressions you can make the system<br />

even more advanced. Let’s say you want to replace all occurrences of '[something]' (the “fields”) with the result<br />

of evaluating something as an expression in Python. Thus, the string<br />

'The sum of 7 and 9 is [7 + 9].'<br />

should be translated to<br />

'The sum of 7 and 9 is 16.'<br />

Also, you want to be able to perform assignments in these fields, so that the string<br />

'[name="Mr. Gumby"]Hello, [name]'<br />

should be translated to<br />

'Hello, Mr. Gumby'<br />

This may sound like a complex task, but let’s review the available tools:<br />

• You can use a regular expression to match the fields and extract their contents.<br />

• You can evaluate the expression strings with eval, supplying the dictionary containing the scope. You<br />

do this in a try/except statement; if a SyntaxError is raised, you probably have a statement (such<br />

as an assignment) on your hands and should use exec instead.<br />

• You can execute the assignment strings (and other statements) with exec, storing the template’s scope<br />

in a dictionary.<br />

• You can use re.sub to substitute the result of the evaluation into the string being processed.<br />

Suddenly it doesn’t look so intimidating, does it?<br />

■Tip If a task seems daunting, it almost always helps to break it down into smaller pieces. Also, take stock<br />

of the tools at your disposal for ideas on how to solve your problem.<br />

See Listing 10-11 for a sample implementation.<br />

Listing 10-11. A Template System<br />

# templates.py<br />

import fileinput, re<br />

# Matches fields enclosed in square brackets:<br />

field_pat = re.compile(r'\[(.+?)\]')

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!