✘Python broken %

Eric S. Raymond esr at thyrsus.com
Fri Sep 9 05:33:11 UTC 2016


Gary E. Miller <gem at rellim.com>:
> Yo All!
> 
> Yet another undocumented Python failure:
> 
> i>>> d = {}
> >>> d[1] = "one"
> >>> d[2] = "two"
> >>> str(d[2])
> 'two'
> >>> echo "%s(d[2])s" % locals
>   File "<stdin>", line 1
>     echo "%s(d[2])s" % locals
>                    ^
> SyntaxError: invalid syntax
> 
> 
> Python says %s(x)s works for any x that str(x) works.
> 
> Here is the Python doc:
> 
> https://docs.python.org/2.7/library/stdtypes.html#string-formatting
> 
> "'s' 	String (converts any Python object using str())."
> 
> WRONG!

No, RIGHT!

The syntax error was triggered by "echo", which isn't a Python keyword.
Your shell reflexes got the better of you <s>and you shot the sheriff.</s>.

If you do the right thing and use print instead, here's what will happen.  The
%s part will stringize the right argument of %, which in this case is a dict;
it will be rendered into a dict literal.  Then it will literally emit the string
"(d[2])s".  If you had any different belief about what would happen, you
misread the documentation.

There is one mildly dangerous curve here.  The syntax of "print" changes in 3.x;
best way to be safe is to use the directive

from __future__ import print_function

which will make recent 2.x versions use functional syntax.

Note to self: Add a section on good Python practice to the Hacking Guide.
-- 
		<a href="http://www.catb.org/~esr/">Eric S. Raymond</a>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 811 bytes
Desc: not available
URL: <http://lists.ntpsec.org/pipermail/devel/attachments/20160909/1b01bbcd/attachment.bin>


More information about the devel mailing list