Python: Tips and Tricks

Printing Local Variables

I was reading a column by dds and he talked about how shell variable substitution was very useful, but it implied that Python didn't support it. It really does support it.

One of the built in functions Python provides is locals(). It returns a dictionary of all the local variables with their names as keys. In concert with the '%' operator's ability to use named variables and dictions, you can do variable substition. I sent dds the following example:

foo = 5
bar = 'a string'
baz = { 'a': 5, bar: foo}
print 'this is bar: %(bar)s, foo: %(foo)d, and baz: %(baz)s' % locals()