I often use the following pattern to format strings.
a = 3
b = 'foo'
c = dict(mykey='myval')
print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars()))
That is, I often have values that I need to print in the local namespace represented by the vars () call. However, when I look through my code, it seems like an awfully unpythonic constantly repeating pattern .format(**vars()).
I would like to create a function that will capture this pattern. It will be something like the following.
def lfmt(s):
"""
lfmt (local format) will format the string using variables
in the caller local namespace.
"""
return s.format(**vars())
Except that by the time I am in the namespace lfmt, vars () is no longer what I want.
How can I write lfmt so that it executes vars () in the namespace of the callers, so that the following code would work as an example above?
print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}'))