Source

stackoverflow / 2201867.py

Full commit
import inspect

a = 3
b = 'foo'
c = dict(mykey='myval')

#prints a is 3, b is foo, mykey is myval
print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars()))

# doesn't work
def lfmt(s):
	"""
	lfmt (local format) will format the string using variables
	in the caller's local namespace.
	"""
	return s.format(**vars())

try:
	print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}'))
except KeyError:
	pass

def lfmt(s):
	"""
	lfmt (local format) will format the string using variables
	in the caller's local namespace.
	"""
	return s.format(**inspect.currentframe().f_back.f_locals)

print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}'))