From: Kevin B. <kb...@ca...> - 2002-03-26 20:53:35
|
I wrote: > hairier than you want: %(Template( {"one":1, "two":4, "four":16, "4":16} > ).format( "Square of four is %(four)s, but the digit 4 is %(4)s" ))s > """ Woops! Just realized I included code using my original Template class name & format method. Gotta remember to run all examples in a new interpreter before posting. :-) This example will work better: import operator class Formatter: def __init__( self, locals=None ): self.locals = locals or globals() def __getitem__( self, name ): return eval( name, self.locals ) asdf=10 template = """asdf=%(asdf)s simple expression=%(20+30)s complex expression=%(reduce(operator.add, range( 10 )))s hairier than you want: %("Square of four is %(four)s, but the digit 4 is %(4)s" % Formatter( {"one":1, "two":4, "four":16, "4":16} ))s """ print template % Formatter() Output: >>> ## working on region in file d:/TEMP/python-318cSW... asdf=10 simple expression=50 complex expression=45 hairier than you want: Square of four is 16, but the digit 4 is 4 >>> (I should also point out that eval may not be blindingly fast, and there are security concerns in evaluating any user-provided expressions...) kb |