[Tutor] __str__ vs. sys.displayhook

Albert-Jan Roskam sjeik_appie at hotmail.com
Sun Mar 20 09:53:04 EDT 2016


Hi,

The other day I was playing with this to make a convenient string version of a named tuple:

>>> from collections import namedtuple as nt
>>> Record = nt("Record", "x y z")
>>> Record.__str__ = lambda self: "| %s |" % " | ".join([item + ": " + str(getattr(self, item)) for item in self._fields])
>>> str(Record(1, 2, 3))
'| x: 1 | y: 2 | z: 3 |'

Then, after reading another discussion on the main Python list (https://www.mail-archive.com/python-list@python.org/msg409771.html) I realized I could do the same thing with a displayhook.
When would I (re)implement __str__, and when would I redefine sys.displayhook? Does the displayhook also affect the way things are logged (with the ' logging'  module)? It feels like sys.displayhook is more " heavy artillery",. but I might be wrong about that.

Thanks in advance for your replies!

Best wishes,
Albert-Jan



 		 	   		  


More information about the Tutor mailing list