Skip to content

Instantly share code, notes, and snippets.

@kilink
Last active September 20, 2015 23:56
Show Gist options
  • Save kilink/a606116313ba46d69e88 to your computer and use it in GitHub Desktop.
Save kilink/a606116313ba46d69e88 to your computer and use it in GitHub Desktop.
local variable string interpolation in Python
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