Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7142

Re: new string formatting with local variables

From Ben Finney <ben+python@benfinney.id.au>
Newsgroups comp.lang.python
Subject Re: new string formatting with local variables
References <BANLkTi=VUwFDv5otq=7CMngbWzHy3Fo50A@mail.gmail.com> <mailman.2491.1307377282.9059.python-list@python.org> <87zklu1ox6.fsf@benfinney.id.au> <4deda1c6$0$29980$c3e8da3$5496439d@news.astraweb.com>
Date 2011-06-07 17:47 +1000
Message-ID <871uz613rl.fsf@benfinney.id.au> (permalink)
Organization Unlimited download news at news.astraweb.com

Show all headers | View raw


Steven D'Aprano <steve+comp.lang.python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Re: new string formatting with local variables Chris Rebert <clp2@rebertia.com> - 2011-06-06 09:21 -0700
  Re: new string formatting with local variables Ben Finney <ben+python@benfinney.id.au> - 2011-06-07 10:11 +1000
    Re: new string formatting with local variables Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-06 18:31 -0600
    Re: new string formatting with local variables Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-06 18:38 -0600
    Re: new string formatting with local variables Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-06-07 03:57 +0000
      Re: new string formatting with local variables Ben Finney <ben+python@benfinney.id.au> - 2011-06-07 17:47 +1000

csiph-web