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



_______________________________________________
Python-3000 mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-3000
Unsubscribe: 
http://mail.python.org/mailman/options/python-3000/archive%40mail-archive.com

Reply via email to