next up previous [pdf]

Next: Loops Up: Integrating Python with SCons Previous: String substitution

Dictionaries

When scripts have a large number of variables, it is often easier to contain them within a Python dictionary instead of letting them float around the script. Dictionaries are declared in key=value format in Python using the dict keyword. For example:

parameters = dict(nx=100,nz=100,verb=True,final_file='output123')

To access variables from within the dictionary, we use list-like indexing where the index given is the name of the variable that we want to access:

nx = parameters['nx'] # Returns 100

We can also set variables within the dictionary, or modify their values after the initial declaration:

parameters['nx'] = 200 # Sets nx to 200
parameters['ny'] = 150 # Adds ny, and sets it to 150

To use the dictionary for string substitution, we only need to modify our formatters to include the key names of the variables that we wish to access from the dictionary. For example:


\begin{verbatimtab}[4]
Flow('model',None,
'''
sfspike n1=%(nx)d n2=%(nz)d
''' % parameters )
\end{verbatimtab}
Notice that the formatters now have the name of the variable inside parentheses: %(nx)d before the formatting expression. Then, the entire dictionary is passed to the string for substitution. At runtime, Python places the values for the keys from the dictionary into the string. If the values are the wrong type, or the key does not exist in the dictionary, then Python will throw an error at runtime, and prevent you from running with a bad value.

By using dictionaries with string substitution, we can add flexibility to our scripts, and improve their readability, which ultimately improves the ability of others to reproduce our work. Thus, you should strive to use dictionaries wherever possible in your SConstructs.


next up previous [pdf]

Next: Loops Up: Integrating Python with SCons Previous: String substitution

2011-11-03