Skip to main content

Advanced Python 3.10 Dataclass for handling monetary values, keeping amount and currency together

Project description

Money dataclass

Advanced Python 3.10 Dataclass for handling monetary values, keeping amount and currency together

This Money class provides a simple and efficient way to manage amounts of money and perform arithmetic operations and comparisons on them. It supports different currencies and ensures that the operations are only performed on matching currencies to avoid inconsistencies.

Features

  • Initialize a Money object with a specific amount and currency.
  • Perform arithmetic operations between Money objects with the same currency.
  • Compare and sort Money objects.
  • Convert a Money object to another currency.
  • Round a Money object to a specified number of decimal places.
  • Serialize and deserialize Money objects to/from JSON.

Usage

from t_money import Money

Creating a Money object

usd = Money(Decimal("10.50"), "USD")

Create a Money object from string

usd_from_str = Money.from_str("USD 5.25")

Arithmetic operations

usd1 = Money(Decimal("10.50"), "USD")
usd2 = Money(Decimal("5.50"), "USD")

usd_sum = usd1 + usd2
usd_difference = usd1 - usd2
usd_product = usd1 * Decimal("2")

Comparisons

print(usd1 == usd2)
print(usd1 < usd2)

Rounding

rounded_usd = usd1.round_to(1)

Currency conversion

eur = usd.convert("EUR", Decimal("0.85"))

Money is hashable

money_set = {usd1, usd2}

Serialization and deserialization

import json

# Serialize data containing Money object
data = {'money': usd}
json_str = json.dumps(data, default=money_serializer)

# Deserialize JSON data to Money object
loaded_data = json.loads(json_str, object_hook=money_deserializer)

Error Handling

When performing operations on Money objects with different currencies, a DifferentCurrencyError will be raised. Make sure to handle this error if necessary when dealing with multiple currencies.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

t_money-0.1.1.tar.gz (5.9 kB view hashes)

Uploaded Source

Built Distribution

t_money-0.1.1-py3-none-any.whl (5.7 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page