变量名后的自动命名关键字参数

时间:2013-05-31 09:49:19

标签: python

我经常发现自己这样做:

myvariable = 'whatever'
another = 'something else'

print '{myvariable} {another}'.format(
    myvariable=myvariable,
    another=another
)

有没有办法不必以这种重复的方式命名关键字参数?我正在考虑这些问题:

format_vars = [myvariable, another]

print '{myvariable} {another}'.format(format_vars)

2 个答案:

答案 0 :(得分:4)

您可以使用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}')

有关此技术的更多详细信息,请参阅Is a string formatter that pulls variables from its calling scope bad practice?

答案 1 :(得分:1)

不确定

>>> format_vars = {"myvariable": "whatever",
...                "another": "something else"}
>>> print('{myvariable} {another}'.format(**format_vars))
whatever something else