Skip to content

Instantly share code, notes, and snippets.

@sbstp
Created May 25, 2018 21:32
Show Gist options
  • Save sbstp/54f1de0d01542b26da85280e8de52b00 to your computer and use it in GitHub Desktop.
Save sbstp/54f1de0d01542b26da85280e8de52b00 to your computer and use it in GitHub Desktop.
Python 3.6 like string formatting
import string
import inspect
class Formatter(string.Formatter):
def __init__(self, f_locals, f_globals):
self._locals = f_locals
self._globals = f_globals
def get_field(self, name, *args, **kwargs):
return (eval(name, self._globals, self._locals), name)
def f(fmt):
frame = inspect.currentframe()
try:
return Formatter(frame.f_back.f_locals, frame.f_back.f_globals).format(fmt)
finally:
del frame
bar = "HEY"
wicked = 5
foo = 3
x = f('foo {bar.lower()!r} {wicked+foo}')
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment