[Python-3000] string.Formatter class

Eric Smith eric+python-dev at trueblade.com
Tue Aug 28 22:33:42 CEST 2007


Eric Smith wrote:
> One of the things that PEP 3101 deliberately under specifies is the 
> Formatter class, leaving decisions up to the implementation.  Now that a 
> working implementation exists, I think it's reasonable to tighten it up.

<examples deleted>

I should also have included the recipe for the 'smart' formatter
mentioned in the PEP, which automatically searches local and global
namespaces:
---------------------
import inspect
from string import Formatter

class SmartFormatter(Formatter):
     def vformat(self, format_string, args, kwargs):
         self.locals = inspect.currentframe(2).f_locals
         return super(SmartFormatter, self).vformat(format_string, args,
                                                    kwargs)

     def get_value(self, key, args, kwargs):
         if isinstance(key, basestring):
             try:
                 # try kwargs first
                 return kwargs[key]
             except KeyError:
                 try:
                     # try locals next
                     return self.locals[key]
                 except KeyError:
                     # try globals last
                     return globals()[key]
         else:
             return args[key]


def func():
     var0 = 'local--0'
     print(fmt.format('in func   0:{var0} 1:{var1}'))

fmt = SmartFormatter()

var0 = 'global-0'
var1 = 'global-1'
func()

print(fmt.format('in module 0:{var0} 1:{var1}'))
---------------------

This code produces:
in func   0:local--0 1:global-1
in module 0:global-0 1:global-1





More information about the Python-3000 mailing list