views:

31

answers:

2

I've got a Python web server (mod_python, if that makes any difference) that I want to start formatting some currency. I've got two pieces of information when I format the currency - the value (as a number) and the currency (as the three-letter ISO 4217 code). I can also retrieve the country (or even city) that the currency is being formatted in. I can expect a large variety of currencies to be formatted - USD, CAD, JPY, GBP, EUR, etc. Each request might be in a different currency.

I'm aware of the locale module, but it doesn't do what I want. That module seems to be based around the computer's locale, so it doesn't work well for formatting any given currency.

Is there a way to do this in Python? Or does anyone know of a good library that can solve this problem?

+1  A: 

I'm sure you could use regex or decimal formatting, but this module seems promising:

http://code.google.com/p/python-money/

Python-money provides carefully designed basic Python primitives for working with money and currencies.

The primary objectives of this module is to aid in the development of financial applications by increasing testability and reusability, reducing code duplication and reducing the risk of defects occurring in the code.

The module defines two basic Python classes -- a Currency class and a Money class. It also pre-defines all the world's currencies, according to the ISO 4217 standard. The classes define some basic operations for working with money, overriding Python's addition, substraction, multiplication, etc. in order to account for working with money in different currencies. They also define currency-aware comparison operators. To avoid floating point precision errors in monetary calculations, the module uses Python's Decimal type exclusively.

The design of the module is based on the Money enterprise design pattern, as described in Martin Fowler's "Patterns of Enterprise Application Architecture".

Dominic Bou-Samra
+1  A: 

For my internationalization needs, I almost invariably turn to ICU, a truly awesome package in both breadth and depth -- usually via pyIcu, although in the past I've had to do some wrapping of my own when pyIcu hadn't yet wrapped some corner of ICU I needed (I'm not sure if they're currently wrapping all the currency-formatting operations you require).

The docs for PyIcu are here, to be read "on top of" ICU's own docs here -- in other words, the PyIcu-specific document is essentially a "phrasebook and dictionary" on how to "translate" ICU's own, C++ focused docs, into docs for PyIcu (and Python-focused ones;-). Yeah, I know, not ideal -- not the only open-source package with imperfect docs I guess (me, I think that's an opportunity for some enterprising soul to write a "PyIcu, the missing manual" book, or the like;-).

Alex Martelli
Or an opportunity to write a documentation translator :)
Steven R. Loomis