This is not a duplicate, as this regards using the newer str.format()
, the above linked question is also of lower quality, and I think this question is sufficiently different to justify its canonicity.
The question:
One might expect an error here, but we can provide the str.format
method with unused keyword arguments.
>>> '{a}{b}'.format(a='foo', b='bar', c='baz')
'foobar'
This enables code like:
>>> foo = 'bar'
>>> baz = 'fizzbuzz'
>>> '{foo}{baz}'.format(**locals())
'barfizzbuzz'
>>> baz = datetime.datetime.now()
>>> '{foo}_{baz}'.format(**locals())
'bar_2013-12-20 18:36:55.624000'
Is this a good practice to do inside a closure like a function?
def make_foo_time_string():
foo = 'bar'
baz = datetime.datetime.now()
return '{foo}{baz}'.format(**locals())
What would be the possible downsides? Extra variables loaded using extra cycles? Is this a matter of convenience? I don't recall seeing this used much, would it be considered idiomatic of Python?
Update I have found a canonical suggested usage using the old style string interpolation: https://wiki.python.org/moin/PythonSpeed/PerformanceTips Nevertheless, it does seem a rather old document.
"Even better, for readability (this has nothing to do with efficiency other than yours as a programmer), use dictionary substitution:"
out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()