py-money
py-money is a Python 3 library that provides `Money` and `Currency` classes for precise monetary calculations. It enforces correct decimal places for currencies, leverages Python's `Decimal` type to prevent floating-point errors, and supports basic arithmetic and logical operations for immutable money objects. The current version is 0.5.0, with releases historically focused on bug fixes and minor feature enhancements.
Warnings
- breaking Direct currency conversion between different `Money` objects is explicitly not supported by design. Attempting to add or subtract `Money` objects of different currencies will raise an error.
- gotcha Instantiating `Money` with floating-point numbers can lead to precision issues. Always use strings or `Decimal` objects for monetary amounts to guarantee accuracy.
- gotcha The library enforces the correct number of decimal places for each currency. Providing an amount with too many decimal places (e.g., '3.678 USD') will raise an error.
- gotcha Rounding is performed after *each* multiplication or division operation. This can lead to different results compared to calculating with higher precision and rounding only at the end of a series of operations.
- deprecated Older versions of `babel` might have caused compatibility issues. Version `0.4.0` was released to allow `py-money` to work with a broader range of `babel` versions (`>= 2.4.0` and `< 3.0`).
- gotcha Prior to v0.3.0, there was no direct support for creating `Money` objects from or converting to currency subunits. This functionality was introduced in v0.3.0.
Install
-
pip install py-money
Imports
- Money
from money.money import Money
- Currency
from money.currency import Currency
- USD
from money.currency import USD
Quickstart
from money.money import Money
from money.currency import USD, EUR
# Create Money objects
price_usd = Money('100.50', USD)
price_eur = Money('50.25', EUR)
# Accessing amount and currency
print(f"USD Price: {price_usd.amount} {price_usd.currency.code}") # Expected: USD Price: 100.50 USD
# Basic arithmetic (same currency)
total_usd = price_usd + Money('9.50', USD)
print(f"Total USD: {total_usd}") # Expected: Total USD: 110.00 USD
# Subtraction
remaining_usd = price_usd - Money('20.00', USD)
print(f"Remaining USD: {remaining_usd}") # Expected: Remaining USD: 80.50 USD
# Multiplication
taxed_price = price_usd * 1.05
print(f"Taxed USD: {taxed_price}") # Expected: Taxed USD: 105.53 USD (due to rounding)
# Division
split_price = price_usd / 2
print(f"Split USD: {split_price}") # Expected: Split USD: 50.25 USD
# Create from subunits (v0.3.0+)
# e.g., 12345 cents for USD
sub_unit_money = Money.from_sub_units(12345, USD)
print(f"From subunits USD: {sub_unit_money}") # Expected: From subunits USD: 123.45 USD
print(f"To subunits USD: {sub_unit_money.sub_units}") # Expected: To subunits USD: 12345