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)
bartekbrak
  • 1,462
  • 1
  • 15
  • 24

2 Answers2

4

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
  • 204,715
  • 48
  • 286
  • 369
1

Sure:

>>> format_vars = {"myvariable": "whatever",
...                "another": "something else"}
>>> print('{myvariable} {another}'.format(**format_vars))
whatever something else
Tim Pietzcker
  • 313,408
  • 56
  • 485
  • 544