04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

248 CHAPTER 10 ■ BATTERIES INCLUDED<br />

# We'll collect variables in this:<br />

scope = {}<br />

# This is used in re.sub:<br />

def replacement(match):<br />

code = match.group(1)<br />

try:<br />

# If the field can be evaluated, return it:<br />

return str(eval(code, scope))<br />

except SyntaxError:<br />

# Otherwise, execute the assignment in the same scope...<br />

exec code in scope<br />

# ...and return an empty string:<br />

return ''<br />

# Get all the text as a single string:<br />

# (There are other ways of doing this; see Chapter 11)<br />

lines = []<br />

for line in fileinput.input():<br />

lines.append(line)<br />

text = ''.join(lines)<br />

# Substitute all the occurrences of the field pattern:<br />

print field_pat.sub(replacement, text)<br />

Simply put, this program does the following:<br />

1. Defines a pattern for matching fields<br />

2. Creates a dictionary to act as a scope for the template<br />

3. Defines a replacement function that does the following:<br />

a. Grabs group 1 from the match and puts it in code.<br />

b. Tries to evaluate code with the scope dictionary as namespace, converts the result to a string, and<br />

returns it. If this succeeds, the field was an expression and everything is fine. Otherwise (i.e., a<br />

SyntaxError is raised), go to Step 3c.<br />

c. Executes the field in the same namespace (the scope dictionary) used for evaluating expressions,<br />

and then returns an empty string (because the assignment doesn’t evaluate to anything).<br />

4. Uses fileinput to read in all available lines, puts them in a list, and joins them into one big string<br />

5. Replaces all occurrences of field_pat using the replacement function in re.sub, and prints the result

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

Saved successfully!

Ooh no, something went wrong!