Strange __str__ behavior

Chris Liechti cliechti at gmx.net
Fri Nov 9 15:32:13 EST 2001


[posted and mailed]

brucehapman at hotmail.com (brucehapman at hotmail.com) wrote in 
news:baf2f841.0111091141.7a104b10 at posting.google.com:

> 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.
> 
...

> 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....

sounds logic for me

> 
> Is this the expected behavior? I was surprised by this.
> 
> TIA,
> b.
> 
> P.S. I want to include a print statement in __str__ not for practical
> purposes, but for mostly didactic purposes when teaching someone
> inheritance.

workaround 1: print to sys.stderr
workaround 2: use a log class:

>>> class Log:
... 	def __init__(self, file):
... 		self.file = file
... 	def msg(self, s):
... 		self.file.write('MESSY %s\n'%s)
... 	def warning(self, s):
... 		self.file.write('WARNING %s\n'%s)
... 	def error(self, s):
... 		self.file.write('ERROR %s\n'%s)
... 
>>> log = Log(sys.stderr)
>>> class Test:
... 	def __str__(self):
... 		log.msg("Hello")
... 		return "Value"
... 
>>> t = Test()
>>> print t
MESSY Hello
Value

you can also print to a file (or TCP port, or Window, or ...). You can also 
add priorities to the messages, or write them to NIL in the final version.
This aproach is more powerful and saved me a lot of time on debugging (i 
have a more complete log class, if you're interested)

writing to files has also the advantage of not to obfuscate the console 
output. (add a flush() after each write() so that you can look at the file 
while ist still open)


-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list