【问题标题】:auto-name keyword arguments after variable names变量名后的自动命名关键字参数
【发布时间】:2013-05-31 09:49:18
【问题描述】:

我经常发现自己这样做:

myvariable = 'whatever'
another = 'something else'

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

有没有办法不必以这种重复的方式命名关键字参数?我在想一些事情:

format_vars = [myvariable, another]

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

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用 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?

    【讨论】:

      【解决方案2】:

      当然:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-29
        • 2015-12-08
        • 2021-08-24
        • 2012-09-29
        • 1970-01-01
        相关资源
        最近更新 更多