print longs

Skip Montanaro skip at mojam.com
Mon Oct 4 20:19:39 EDT 1999


    >> Do I have to convert to a string and manually pull the 'L' off?

    Greg> Unfortunately, yes. Many other people think this is a pain as
    Greg> well, but Guido doesn't seem to be among them, so we're stuck with
    Greg> this for the time being.

I can't read Guido's mind, but I don't think that's the reason str and repr
work the way they do.  repr and str are supposed to provide you with string
representations that are suitable to convey the object's meaning in a couple
different contexts, one being readability by humans and one being to later
reparse the string (by eval for example).  If they displayed 2L**38 as
'274877906944', instead of '274877906944L', I'd consider them broken, since
essential information about the object's type is lost.

People that deal with numbers that represent monetary figures might lament
the fact that numbers are not formatted automatically with commas, points or
spaces inserted in the right spots.  That doesn't make the current display
format incorrect, just inappropriate for that application.

If you want no-L print behavior automatically, simply implement a UserLong
class (analogous to UserList/UserDict) that behaves like a long but has
suitable __repr__ and __str__ methods:

    class UserLong:
      def __init__(self, val):
	self.val = val
      def __repr__(self):
	return repr(self.val)[:-1]
      __str__ = __repr__
      ... arithmetic ignored ...

    >>> u = UserLong(2L**38)
    >>> u
    274877906944

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list