-
-
Save kilink/a606116313ba46d69e88 to your computer and use it in GitHub Desktop.
local variable string interpolation in Python
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 | |
import sys | |
class T(object): | |
pattern = re.compile("#{(.+)}") | |
currentframe = inspect.currentframe | |
def __call__(self, template): | |
try: | |
frame = self.currentframe().f_back | |
context = frame.f_globals.copy() | |
context.update(frame.f_locals) | |
finally: | |
del frame | |
def sub(match): | |
return str(context[match.group(1)]) | |
return self.pattern.sub(sub, template) | |
sys.modules[__name__] = T() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment