Why does Python do this?

Steven Taschuk staschuk at telusplanet.net
Fri Jul 25 17:22:13 EDT 2003


Quoth Gre7g Luterman:
  [...]
> Python 2.2.2 (#3, Jun 16 2003, 19:11:56)
  [...]
> >>> class b:
> ...   def __str__(self):
> ...     print "printed"
> ...     return "returned"
  [...]
> >>> print y
>  printed
> returned
> 
> Note the extra space printed when I executed the "print y" command.

I don't know why this happens in 2.2, but I observe that it
doesn't in 2.3.  Presumably some softspace fix has been made.

> At first I thought it was just a quirk of the print command being
> interrupted by another, but I don't think it is quite that simple.  Note
> that:
  [...]
> >>> print str(y)
> printed
> returned
  [...]
> So it only seems to happen when you interrupt a print statement with
> another print statement during an implicit string conversion.

Indeed -- because that's the only way to actually "interrupt" one
print statement with another.  Consider the bytecode:

    >>> def bar(x):
    ...     print str(x)
    ... 
    >>> dis.dis(bar)
      2           0 LOAD_GLOBAL              0 (str)
                  3 LOAD_FAST                0 (x)
                  6 CALL_FUNCTION            1
                  9 PRINT_ITEM          
                 10 PRINT_NEWLINE       
                 11 LOAD_CONST               0 (None)
                 14 RETURN_VALUE 

Here the "inner" print statement occurs during the function call
(6), entirely before (hence not interrupting) the "outer" print
statement (9).

-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list