[Pythonmac-SIG] Re: Number format in IDE

Jacob Kaplan-Moss jacobkm@cats.ucsc.edu
Mon, 27 Aug 2001 01:06:44 +0100


>Okay, I know about this, but it would be nice if there was a way of setting
>the output default format, so that when you are using it as a desk
>calculator it doesn't look icky, and then in another circumstance when you
>don't want to be "lied to" to be able to change it back. Sure it may be
>instructive for computer science students to see this sort of thing, but
>math students have too many other things on their mind. Even $20 calculators
>can do that with their mode buttons. I can't overwrite the repr function for
>float class can I? I suppose I could create a subclass of floating point
>that behaved just like normal floating point, but had a different repr, but
>still that would be a bit of a pain, because you would have to write the
>class name every time you used it.

One thing to try is sys.displayhook (exists in Python 2.1 and later IIRC).

I couldn't find much documentation on the displayhook online; PEP 217 
is probably your best bet:

http://python.sourceforge.net/peps/pep-0217.html

Basically, you assign a function to sys.displayhook and subsequent 
implicit displays (without an explicit "print", that is) get routed 
through your new display hook.  Be careful: sys.displayhook is also 
responsible for assigning the value of the last expression to _, so 
if you forget to do this you may be in trouble.

Here's a little interactive playing around I did to try to get what 
you're looking for:

Python 2.1 (#92, Apr 24 2001, 23:59:23)  [CW PPC GUSI2 THREADS] on mac
Type "copyright", "credits" or "license" for more information.

>>>  import sys
>>>  import __builtin__
>>>  def mydisplayhook(o):
...	if type(o) == type(0.1):
...		# print a better looking float
...		print str(o)
...		# remember to assign to _!
...		__builtin__._ = o
...	else:
...		#use the old displayhook in every other case
...		sys.__displayhook__(o)
...
>>>  x = 5.1
>>>  x
5.0999999999999996
>>>  sys.displayhook = mydisplayhook
>>>  x
5.1
>>>  # wahoo!

Hope that helps!

Jacob