Skip to content

Instantly share code, notes, and snippets.

@sbstp
Last active February 28, 2018 19:29
Show Gist options
  • Save sbstp/4773691bf8f91a75d03f6ad0066900cb to your computer and use it in GitHub Desktop.
Save sbstp/4773691bf8f91a75d03f6ad0066900cb to your computer and use it in GitHub Desktop.
import inspect
from collections import ChainMap
def f(fmt):
frame = inspect.currentframe()
try:
vars = ChainMap(frame.f_back.f_locals, frame.f_back.f_globals)
# from pprint import pprint
# pprint(vars)
return fmt.format(**vars)
finally:
del frame
name = "simon"
movie = "groundhog day"
print(f("{name}'s favorite movie is {movie}."))
# Prints: simon's favorite movie is groundhog day.
def outer():
movie = "american psycho" # Supports scoping properly.
def inner():
nonlocal movie # Required for f to find the movie variable, globals don't need to be listed here i.e. `name`.
# Without nonlocal, the global `movie` variable is used. If there were no global named `movie`, it would
# raise an exception.
print(f("{name}'s favorite movie is {movie}."))
# Prints: simon's favorite movie is american psycho.
inner()
outer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment