Is a string formatter that pulls variables from its calling scope bad practice?
- by Eric
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, ...)
Where I'm trying to interpolate a large number of variables into a large string.
Is there a good reason not to write a function like this that uses the inspect module to find variables to interpolate?
import inspect
def interpolate(s):
return s.format(**inspect.currentframe().f_back.f_locals)
def generateTheString(x):
y = foo(x)
z = x + y
# more calculations go here
return interpolate("{x}, {y}, {z}")