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.

 

Comment:

This makes sense so far. It would be helpful to consider a couple of additional issues, and then make some concrete recommendations. (I don't offer anything concrete though!) First, how would one represent which type of currency a particular value represented? Would there be one subclass for US$, one for UK£, etc.? Would this just be represented by a member variable? No matter how this is represented, could one specify a standard way of performing conversions (triggered by calling the constructor, or performing mixed arithmetic)? Maybe a "with" statement could encapsulate the exchange rates to be used in the calculations it encloses. I suggest that internal representations should be of the decimal type. Methods for converting to other forms could be useful, but for sake of correctness I wouldn't want to round-trip anything back into money after it was cast to int or float. Maybe there could be a standard way of accumulating distributive rounding errors (i.e., with computer math the distributive rule is sometimes violated, and in many applications we need to keep track of the difference), although that's probably a second-order concern.

Posted by Jess Austin (2007-03-21)

A Django site. rendered by a django application. hosted by webfaction.