[Tutor] modulus

Wayne Werner waynejwerner at gmail.com
Wed Nov 16 23:29:26 CET 2011


On Wed, Nov 16, 2011 at 4:04 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Wayne Werner wrote:
>
>> <snip> It was explained to me once that in
>
>  this case:
>>
>> "%s" % 42
>>
>> That since python expects to see a single-element tuple it treats it as or
>> converts 42 to a single element tuple.
>>
>
> "Treats as" may be true; "converts to" not so much. What it actually does
> is this:
>
> py> import dis
> py> dis.dis(compile('"%s" % x', '', 'single'))
>  1           0 LOAD_CONST               0 ('%s')
>              3 LOAD_NAME                0 (x)
>              6 BINARY_MODULO
>              7 PRINT_EXPR
>              8 LOAD_CONST               1 (None)
>             11 RETURN_VALUE
>
>
> 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.
>
> 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.


Ah, very cool. Just because I was interested, I did the same thing, only
using (x,) and there was only one difference (line? 6):

>>> dis.dis(compile('"%s" % (x, )', '', 'single'))
  1           0 LOAD_CONST               0 ('%s')
              3 LOAD_NAME                0 (x)
              6 BUILD_TUPLE              1
              9 BINARY_MODULO
             10 PRINT_EXPR
             11 LOAD_CONST               1 (None)
             14 RETURN_VALUE

<PSA tune>
The more you know!

Thanks,
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111116/41f2b61b/attachment.html>


More information about the Tutor mailing list