更新: Python 3.6 内置了这个特性(一个更强大的变体):
x, y, z = range(3)
print(f"{x} {y + z}")
# -> 0 3
参见PEP 0498 -- 文字字符串插值
它[手动解决方案]导致嵌套函数的行为有些令人惊讶:
from callerscope import format
def outer():
def inner():
nonlocal a
try:
print(format("{a} {b}"))
except KeyError as e:
assert e.args[0] == 'b'
else:
assert 0
def inner_read_b():
nonlocal a
print(b) # read `b` from outer()
try:
print(format("{a} {b}"))
except KeyError as e:
assert 0
a, b = "ab"
inner()
inner_read_b()
注意:相同的调用成功或失败取决于变量是否在其上方或下方提及。
在哪里callerscope
:
import inspect
from collections import ChainMap
from string import Formatter
def format(format_string, *args, _format=Formatter().vformat, **kwargs):
caller_locals = inspect.currentframe().f_back.f_locals
return _format(format_string, args, ChainMap(kwargs, caller_locals))