Wednesday, December 30, 2009

"Python Trick" % locals()

I just learned this python trick for string formatting. Here's an example:
def compileCommand(sourcePath, outputPath):
switches = "-O0 -g"
return "gcc -c %(switches)s %(sourcePath)s -o %(outputPath)" % locals()
This trick uses the dict locals() to supply the values for formatting the string with the '%' signs in it. The names inside the parens are resolved with the local variable names in the function.

Example usage of the above function:
cmd = compileCommand("hello.c", "hello.o")
assert cmd == "gcc -c -O0 -g hello.c -o hello.o"

2 comments:

DopplerDeffect said...

Thats the old way of string formatting, the new way would be:

return "gcc -c {switches} {sourcePath} -o {outputPath}".format(**locals())

I much prefer the str.format function over the '"%s" % variable' method

thejoshwolfe said...

That does look a lot better. However, it's not available until Python 2.6. At work, I'm writing in Python 2.4.