更新: 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))