Is a string formatter that pulls variables from its calling scope bad practice?

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2012-11-09T16:42:21Z Indexed on 2012/11/09 17:00 UTC
Read the original article Hit count: 155

Filed under:

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}")

© Stack Overflow or respective owner

Related posts about python