Strange __str__ behavior

brucehapman at brucehapman at
Fri Nov 9 20:41:06 CET 2001

I am defining a class w/ method __str__. If I put a print statement
inside __str__, and if I then use the print statement to display an
instance of the class, I get an extra space in the output.


Python 2.2b1 (#25, Oct 19 2001, 11:44:52) [MSC 32 bit (Intel)] on
Type "help", "copyright", "credits" or "license" for more information.
>>> class Test:
...     def __str__(self):
...         print "In method Test.__str__"
...         return "String representation of instance."
>>> test = Test()
>>> print test       # causes extra space problem
 In method Test.__str__
String representation of instance.


Language reference section 6.6, "The print statement", says

A space is written before each object is (converted and) written,
unless the output system believes it is positioned at the beginning of
a line. This is the case (1) when no characters have yet been written
to standard output, (2) when the last character written to standard
output is "\n", or (3) when the last write operation on standard
output was not a print statement. (In some cases it may be functional
to write an empty string to standard output for this reason.)

I would think that case 1 applies here. Am I wrong? Does the print
statement in __str__ somehow know that the print statement in the main
program has or will print characters to stdout? Perhaps the "output
system" knows that one print statement (the outer print statement) has
executed or is executing, so the second (inner) print statement causes
the output system to print a space....

Is this the expected behavior? I was surprised by this.


P.S. I want to include a print statement in __str__ not for practical
purposes, but for mostly didactic purposes when teaching someone

More information about the Python-list mailing list