[Python-Dev] prePEP: Money data type

Alex Martelli aleaxit at yahoo.com
Mon Oct 20 11:26:57 EDT 2003

On Monday 20 October 2003 04:41 pm, Batista, Facundo wrote:
> #- FWIW, Rogue Wave's Money class lets you specify _either_ rounding
> #- approach -- ROUND_PLAIN specifies EU-rules-compliant rounding,
> #- ROUND_BANKERS specifies round-to-even, for exactly in-between
> #- isn't ONE right thing, it depends on locale &c:-(.
> Seems to me that the best would be to have two functions (liked the names
> roundPlain and roundBankers), and the behaviour to be specified by the

Sure, rounding IS best set by function, though you may want more than
two (roundForbid to raise exceptions when rounding tries to happen,
roundTruncate, etc).

> user. But here I found two approaches:
> 	- By argument: Redefine the sintaxis with Money(value, [precision],
> [round]), having a specified default for round.
> 	- By subclassing: Just make:
> 		class MyMoney(Money):
> 			moneyround = roundPlain
> The first is better in the way that you use Money directly, but you need to
> specify *always* the rounding. In the second way you have to subclass it

They're not at all incompatible!

class Money:
    round = staticmethod(roundWhateverDefault)
    precision = someDefaultPrecision
    def __init__(self, value, precision=None, round=None):
        self.value = value
        if precision is not None: self.precision = precision
        if round is not None: self.round = round

then use self.precision and self.round in all further methods -- they'll
correctly go to either the INSTANCE attribute, if specifically set, or
the CLASS attribute, if no instance attribute is set.  A useful part of
how Python works, btw.

So you can subclass Money and change the default rounding without
any problem whatsoever.

> one time, but then all the job is done (anyway, maybe you was already
> subclassing Money to change it decimalSeparator or something).

I do NOT think any advanced formatting should be part of the responsibilities
of class Money itself.  I would focus on correct and complete arithmetic with
good handling of exact precision and rounding rules: I contend THAT is the
really necessary part.  One can always subclass Money to ADD data and
methods (e.g. with appropriately designed mix-ins), but remember subclassing 
cannot REMOVE capabilities: so, avoid the "fat base class" syndrome, a
well-recognized anti-pattern, and make sure what you put in a base class is
what's needed for ALL uses of it.


More information about the Python-Dev mailing list