Why does Python do this?
staschuk at telusplanet.net
Fri Jul 25 23:22:13 CEST 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
> 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
> >>> print str(y)
> 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)
2 0 LOAD_GLOBAL 0 (str)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1
11 LOAD_CONST 0 (None)
Here the "inner" print statement occurs during the function call
(6), entirely before (hence not interrupting) the "outer" print
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