我经常发现自己这样做:
myvariable = 'whatever'
another = 'something else'
print '{myvariable} {another}'.format(
myvariable=myvariable,
another=another
)
是否有一种方法可以避免以这种重复的方式命名关键字参数?我在想这样的事情:
format_vars = [myvariable, another]
print '{myvariable} {another}'.format(format_vars)
可以使用locals():
print '{myvariable} {another}'.format(**locals())
也可以(至少在Cpython中)自动从作用域中选择格式变量,例如:
def f(s, *args, **kwargs):
frame = sys._getframe(1)
d = {}
d.update(frame.f_globals)
d.update(frame.f_locals)
d.update(kwargs)
return Formatter().vformat(s, args, d)
用法:
myvariable = 'whatever'
another = 'something else'
print f('{myvariable} {another}')
参见从其调用范围中提取变量的字符串格式化程序是坏做法吗?有关此技术的详细信息。
当然:
>>> format_vars = {"myvariable": "whatever",
... "another": "something else"}
>>> print('{myvariable} {another}'.format(**format_vars))
whatever something else