new string formatting with local variables
Ben Finney
ben+python at benfinney.id.au
Tue Jun 7 03:47:58 EDT 2011
Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
> On Tue, 07 Jun 2011 10:11:01 +1000, Ben Finney wrote:
>
> > I tend to use ‘u"foo {bar} baz".format(**vars())’, since ‘vars’ can
> > also take the namespace of an object. I only need to remember one
> > “give me the namespace” function for formatting.
[…]
>
> It's a code smell. Why is this code messing with locals() instead of
> using names explicitly? Is it possible that this code will attempt to
> modify locals()? I need to look twice to be sure its safe. Why do you
> need to pass *all* of the locals if only two names are used?
The names are explicit; they're in the format string. It's because I
don't want to repeat the names several times that I'm making use of the
dictionary provided by ‘vars()’.
> Where possible, I'd rather be explicit about which names I want:
>
> solo = "Han Solo"
> jabba = "Jabba the Hutt"
>
> "{hero} was captured by {villain}.".format(hero=solo, villain=jabba)
See, repeating those name references makes *me* hinky. I used those
names because they refer to things I've already named.
--
\ “The difference between religions and cults is determined by |
`\ how much real estate is owned.” —Frank Zappa |
_o__) |
Ben Finney
More information about the Python-list
mailing list