1

I often find myself doing this:

myvariable = 'whatever'
another = 'something else'

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

Is there a way not to have to name the keyword arguments in this repetitive manner? I'm thinking something along these lines:

format_vars = [myvariable, another]

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

2 Answers2

3

You can use locals():

print '{myvariable} {another}'.format(**locals())

It's also possible (in Cpython at least) to pick format variables automatically from the scope, for example:

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)    

Usage:

myvariable = 'whatever'
another = 'something else'

print f('{myvariable} {another}')

See Is a string formatter that pulls variables from its calling scope bad practice? for more details about this technique.

Community
  • 1
  • 1
georg
  • 211,518
  • 52
  • 313
  • 390
1

Sure:

>>> format_vars = {"myvariable": "whatever",
...                "another": "something else"}
>>> print('{myvariable} {another}'.format(**format_vars))
whatever something else
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561