new string formatting with local variables

Ian Kelly ian.g.kelly at gmail.com
Mon Jun 6 20:38:10 EDT 2011


On Mon, Jun 6, 2011 at 6:11 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Chris Rebert <clp2 at rebertia.com> writes:
>
>> print "{solo} was captured by {jabba}".format(**locals()) # RIGHT
>
> 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.

If you're using an object namespace, then you can just do this:

print("{o.solo} was captured by {o.jabba}".format(o=self))

That looks a lot cleaner to me than passing in **vars(self).  For
locals(), I can see the appeal, but I tend to avoid it because it has
the same icky feeling as doing an import *.

Cheers,
Ian



More information about the Python-list mailing list