Last active
April 18, 2017 23:19
-
-
Save m1m0r1/e0da19cc4a9372cb7850c1a485e200e0 to your computer and use it in GitHub Desktop.
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
def format(st, *args, **kwds): | |
""" Format with string interpolation | |
String interpolation for python version < 3.6 | |
See also | |
- https://www.python.org/dev/peps/pep-0498/ | |
- http://stackoverflow.com/questions/6618795/get-locals-from-calling-namespace-in-python | |
""" | |
>>> a = 1 | |
>>> b = 2 | |
>>> format('{a} + {a} = {b}') | |
'1 + 1 = 2' | |
>>> format('{a} + {a} != {b}', b=3) | |
'1 + 1 != 3' | |
>>> format('{a} + {0} = {b}', 2, b=3) | |
'1 + 2 = 3' | |
# TODO access to external variables | |
# >>> def nested1(): | |
# ... a = 2 | |
# ... def nested2(): | |
# ... return format('{a} = {a} = {b}') | |
# ... return nested2() | |
# >>> nested1() | |
# '2 = 2 = 2' | |
""" | |
import inspect | |
frame = inspect.currentframe() | |
try: | |
d = {} | |
d.update(frame.f_back.f_globals) | |
d.update(frame.f_back.f_locals) | |
d.update(kwds) | |
return st.format(*args, **d) | |
finally: | |
del frame |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment