We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

Idea: Adding a Money Base Type

February 8, 2002 | Fredrik Lundh

I propose adding an “abstract” base type for money objects, which can be subclassed by actual implementations.

The base type allows the user to use isinstance to identify an object as a money object, and convert the money value to an integer, a floating point value, or a well-formed string.

The goal is not to standardize any behaviour beyond this; anything else should be provided by implementation subtypes.

The Base Type

The basemoney type provides a minimal interface, with five standard methods.

class basemoney(object):

    def __str__(self):
       # return the money value, as a string that should
       # match the regular pattern "[+|-]?\d+(.\d+)?"
       # use trailing zeros to indicate precision

    def __int__(self):
       # convert money value to an integer.  may return a
       # long integer, if necessary

    def __float__(self):
       # convert money value to a float.

    def __hash__(self):
       # return hash value.  could be defined as hash(str(self))

    def __cmp__(self, other):
       # compare two money values

Note that int() and float() might be inexact.

Questions

None, this far.