A slight adaptation from the NamespaceFormatter example in PEP-3101:
import string
class NamespaceFormatter(string.Formatter):
def __init__(self, namespace={}):
super(NamespaceFormatter, self).__init__()
self.namespace = namespace
def get_value(self, key, args, kwds):
if isinstance(key, str):
try:
# Check explicitly passed arguments first
return kwds[key]
except KeyError:
return self.namespace[key]
else:
super(NamespaceFormatter, self).get_value(key, args, kwds)
fmt = NamespaceFormatter(globals())
fruit = 'Pear'
print fmt.format('Hey, {fruit}!')
for:
Hey, Pear!