What is this syntax ?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jun 19 19:19:56 EDT 2011


On Sun, 19 Jun 2011 23:06:36 +0200, Vito 'ZeD' De Tullio wrote:

> well, in python3 you can use dict to format strings
> 
>>>> print("%(a)s" % {'a':'b'})
> b

It's not just Python 3. That bit of functionality goes back all the way 
to Python 1.5, which is the oldest version I have installed.

In Python 2.6 on up, you can also use the new format() method on strings:

>>> '{a}'.format(a='spam')
'spam'


> and you can achieve php interpolation via locals()
> 
>>>> a = 'b'
>>>> print("%(a)s" % locals())
> b

You can do that, but when reading code I consider any direct use of 
locals() (and globals() for that matter) to be a code smell: not 
necessarily wrong in and of itself, but unusual and suspicious enough to 
be worth a second, careful, look. As such, I would want to think long and 
hard before inflicting it on others by using it myself.

For those unfamiliar with the idea of code smells:

http://www.joelonsoftware.com/articles/Wrong.html



-- 
Steven



More information about the Python-list mailing list