I have some code that does an awful lot of string formatting, Often, I end up with code along the lines of:
\"...\".format(x=x, y=y, z=z, foo=foo, ...)
The good old mailman has a function _ that does exactly this thing:
def _(s):
if s == '':
return s
assert s
# Do translation of the given string into the current language, and do
# Ping-string interpolation into the resulting string.
#
# This lets you write something like:
#
# now = time.ctime(time.time())
# print _('The current time is: %(now)s')
#
# and have it Just Work. Note that the lookup order for keys in the
# original string is 1) locals dictionary, 2) globals dictionary.
#
# First, get the frame of the caller
frame = sys._getframe(1)
# A `safe' dictionary is used so we won't get an exception if there's a
# missing key in the dictionary.
dict = SafeDict(frame.f_globals.copy())
dict.update(frame.f_locals)
# Translate the string, then interpolate into it.
return _translation.gettext(s) % dict
So if Barry Warsaw can do that, why can't we?