Skip to content

Instantly share code, notes, and snippets.

@m1m0r1
Last active April 18, 2017 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1m0r1/e0da19cc4a9372cb7850c1a485e200e0 to your computer and use it in GitHub Desktop.
Save m1m0r1/e0da19cc4a9372cb7850c1a485e200e0 to your computer and use it in GitHub Desktop.
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