Skip to content

carlospalol/money

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Python Money

Money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.

This is version 1.4.0-dev.

Development

https://github.com/carlospalol/money

Latest release

https://pypi.python.org/pypi/money/

This package is compatible with Python 2.7, 3.4, 3.5, but there are important Differences between Python versions. All code examples use Python 3.5.

Contents

Installation

Install the latest release with:

pip install money

For locale-aware formatting, also install the latest version of Babel (2.2 or 2.3 required):

pip install babel

Usage

amount can be any valid value in decimal.Decimal(value) and currency should be a three-letter currency code. Money objects are immutable by convention and hashable. Once created, you can use read-only properties amount (decimal.Decimal) and currency (str) to access its internal components:

Money emulates a numeric type and you can apply most arithmetic and comparison operators between money objects, as well as addition, subtraction, and division with integers (int) and decimal numbers (decimal.Decimal):

More formally, with AAA and BBB being different currencies:

+-----------+---------------+-----------+-----------+-----------------+ | | Operator | Money AAA | Money BBB | int, Decimal | +===========+===============+===========+===========+=================+ | Money | ``+``, ``-`` | Money | N/A | Money | + AAA +---------------+-----------+-----------+-----------------+ | | * | N/A | N/A | Money | + +---------------+-----------+-----------+-----------------+ | | /, // | Decimal | N/A | Money | + +---------------+-----------+-----------+-----------------+ | | >, >= | Compares | N/A | N/A | | | <, <= | amount. | | | + +---------------+ +-----------+-----------------+ | | == | | False | False | | | | | | | +-----------+---------------+-----------+-----------+-----------------+

Arithmetic operations with floats are not directly supported. If you need to operate with floats, you must first convert the float to a Decimal, or the Money object to a float (i.e. float(m)). Please be aware of the issues and limitations of floating point arithmetics.

Currency presets

If you use fixed currencies in your code, you may find convenient to create currency-preset Money subclasses:

Formatting

Money objects are printed by default with en_US formatting and the currency code.

Use format(locale=LC_NUMERIC, pattern=None, currency_digits=True, format_type='standard') for locale-aware formatting with currency expansion. format() relies on babel.numbers.format_currency(), and requires Babel to be installed.

The character \xa0 is an unicode non-breaking space. If no locale is passed, Babel will use your system's locale. You can also provide a specific pattern to format():

For more details on formatting see Babel docs on currency formatting. To learn more about the formatting pattern syntax check out Unicode TR35.

Currency exchange

Currency exchange works by "installing" a backend class that implements the abstract base class (abc) money.exchange.BackendBase. Its API is exposed through money.xrates, along with setup functions xrates.install(pythonpath), xrates.uninstall(), and xrates.backend_name.

A simple proof-of-concept backend money.exchange.SimpleBackend is included:

XMoney

You can use money.XMoney (a subclass of Money), for automatic currency conversion while adding, subtracting, and dividing money objects (+, +=, -, -=, /, //). This is useful when aggregating lots of money objects with heterogeneous currencies. The currency of the leftmost object has priority.

Exceptions

Found in money.exceptions.

MoneyException(Exception)

Base class for all exceptions.

CurrencyMismatch(MoneyException, ValueError)

Thrown when mixing different currencies, e.g. Money(2, 'EUR') + Money(2, 'USD'). Money objects must be converted first to the same currency, or XMoney could be used for automatic conversion.

InvalidOperandType(MoneyException, TypeError)

Thrown when attempting invalid operations, e.g. multiplication between money objects.

ExchangeError(MoneyException)

Base class for exchange exceptions.

ExchangeBackendNotInstalled(ExchangeError)

Thrown if a conversion is attempted, but there is no backend available.

ExchangeRateNotFound(ExchangeError)

The installed backend failed to provide a suitable exchange rate between the origin and target currencies.

Hierarchy

  • MoneyException
    • CurrencyMismatch
    • InvalidOperandType
    • ExchangeError
      • ExchangeBackendNotInstalled
      • ExchangeRateNotFound

Differences between Python versions

Expression Python 2.x Python 3.x
round(Money('2.5', 'EUR')) Returns 3.0, a float rounded amount away from zero. Returns EUR 2, a Money object with rounded amount to the nearest even.
Money('0', 'EUR').amount < '0' Returns True. This is the weird but expected behaviour in Python 2.x when comparing Decimal objects with non-numerical objects (Note the '0' is a string). See note in docs. TypeError: unorderable types: decimal.Decimal() > str()

Design decisions

There are several design decisions in money that differ from currently available money class implementations:

Localization

Do not keep any kind of locale conventions database inside this package. Locale conventions are extensive and change over time; keeping track of them is a project of its own. There is already such a project and database (the Unicode Common Locale Data Repository), and an excellent python API for it: Babel.

Currency

There is no need for a currency class. A currency is fully identified by its ISO 4217 code, and localization or exchange rates data are expected to be centralized as databases/services because of their changing nature.

Also:

  • Modulo operator (%): do not override to mean "percentage".
  • Numeric type: you can mix numbers and money in binary operations, and objects evaluate to False if their amount is zero.
  • Global default currency: subclassing is a safer solution.

Contributions

Contributions are welcome. You can use the regular github mechanisms.

To test your changes you will need tox and python 2.7, 3.4, and 3.5. Simply cd to the package root (by setup.py) and run tox.

License

money is released under the MIT license, which can be found in the file LICENSE.

About

Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages