Why does Python do this?

Gre7g Luterman gre7g-d-1059579503.1d83b3 at wolfhome.com
Fri Jul 25 11:38:30 EDT 2003


I realize this is a rather queer example, but I would expect the
following two classes to act the same basic way.  Does anyone know why
they do not?

Python 2.2.2 (#3, Jun 16 2003, 19:11:56)
[GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> class a:
...   def __str__(self):
...     sys.stdout.write("written\n")
...     return "returned"
...
>>> class b:
...   def __str__(self):
...     print "printed"
...     return "returned"
...
>>> x=a(); y=b()
>>> print x
written
returned
>>> print y
 printed
returned

Note the extra space printed when I executed the "print y" command.

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(x)
written
returned
>>> print str(y)
printed
returned
>>> print x.__str__()
written
returned
>>> print y.__str__()
printed
returned

work just as you might expect.

Here's another variation:

>>> import sys
>>> def a():
...   sys.stdout.write("written\n")
...   return "returned"
...
>>> def b():
...   print "printed"
...   return "returned"
...
>>> print a()
written
returned
>>> print b()
printed
returned

which works as expected.

So it only seems to happen when you interrupt a print statement with
another print statement during an implicit string conversion.

Any guesses?

Gre7g.





More information about the Python-list mailing list