Last active
February 28, 2018 19:29
-
-
Save sbstp/4773691bf8f91a75d03f6ad0066900cb 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
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