<div class="gmail_quote">On Wed, Nov 16, 2011 at 4:04 PM, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve@pearwood.info">steve@pearwood.info</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="im">Wayne Werner wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span style="background-color: transparent; "><snip> It was explained to me once that in</span></blockquote></div>
<div class="im"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
this case:<br>
<br>
"%s" % 42<br>
<br>
That since python expects to see a single-element tuple it treats it as or<br>
converts 42 to a single element tuple.<br>
</blockquote>
<br></div>
"Treats as" may be true; "converts to" not so much. What it actually does is this:<br>
<br>
py> import dis<br>
py> dis.dis(compile('"%s" % x', '', 'single'))<br>
1 0 LOAD_CONST 0 ('%s')<br>
3 LOAD_NAME 0 (x)<br>
6 BINARY_MODULO<br>
7 PRINT_EXPR<br>
8 LOAD_CONST 1 (None)<br>
11 RETURN_VALUE<br>
<br>
<br>
Notice that the call to BINARY_MODULO (the % operator) takes two arguments, the string "%s" and the object x, whatever it happens to be. Python can't convert x to a tuple at this point, because it doesn't know what x is, and it may not know how many format specifiers are in the string either.<br>
<br>
Once the string and the object hit BINARY_MODULO, all bets are off. It will do whatever it likes, because that's purely internal implementation.</blockquote><div><br></div><div>Ah, very cool. Just because I was interested, I did the same thing, only using (x,) and there was only one difference (line? 6):</div>
<div><br></div><div><span style="background-color: transparent; ">>>> dis.dis(compile('"%s" % (x, )', '', 'single'))</span></div><div> 1 0 LOAD_CONST 0 ('%s')</div>
<div> 3 LOAD_NAME 0 (x)</div><div> 6 BUILD_TUPLE 1</div><div> 9 BINARY_MODULO</div><div> 10 PRINT_EXPR</div><div> 11 LOAD_CONST 1 (None)</div>
<div> 14 RETURN_VALUE</div><div><br></div><div><PSA tune></div><div>The more you know!</div><div><br></div><div>Thanks,</div><div>-Wayne</div></div>