Created
May 25, 2018 21:32
-
-
Save sbstp/54f1de0d01542b26da85280e8de52b00 to your computer and use it in GitHub Desktop.
Python 3.6 like string formatting
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 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