Last active
February 7, 2016 00:08
-
-
Save bholt/2aab27c2e562b6d98a02 to your computer and use it in GitHub Desktop.
String interpolation in Python 2 using `eval` and `inspect` to get caller's locals.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
import re | |
def fmt(s): | |
""" | |
Interpolate arbitrary expressions inside '{}' in strings (similar to Ruby or Scala). | |
It should go without saying that because this uses `eval`, it is unsafe to use with any user-provided inputs. | |
It is also probably terribly slow because it's using `inspect` to get the caller's local variables. | |
Example: | |
x = 1 | |
print fmt('x is {x}, x+1 is {x+1}') | |
> x is 1, x+1 is 2 | |
""" | |
caller_locals = inspect.currentframe().f_back.f_locals | |
return re.compile(r"{(.*?)}").sub(lambda m: str(eval(m.group(1), globals(), caller_locals)), str(s)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment