Skip to main content

finance-types

Financial scalar types with optional Django and Django REST Framework fields. Use validated country codes, currency codes, decimal amounts, percentages, and money in Python applications. Install optional adapters for Django models, forms, and REST APIs.

Install

pip install finance-types
pip install 'finance-types[formatting]'
pip install 'finance-types[django]'
pip install 'finance-types[drf]'

Core imports require only pycountry. They do not import Django, DRF, or Babel.

Core example

from decimal import Decimal, ROUND_DOWN
from finance_types import Country, Currency, Money, Percentage

assert Country("IR") == "IR"
assert Currency("IRR") == "IRR"
subtotal = Money("12.345", "USD")
assert round(subtotal).amount == Decimal("12.35")
assert (subtotal * 2).amount == Decimal("24.690")
assert Percentage("0.15").to_100() == Decimal("15")
truncated = subtotal.copy(rounding=ROUND_DOWN)
assert round(truncated).amount == Decimal("12.34")
assert truncated.copy().rounding == ROUND_DOWN

Decimal contracts

BoundedDecimal, NonNegativeAmount, PositiveAmount, Percentage, and Percentage100 are Decimal subclasses. They reject Infinity, negative Infinity, NaN, and signaling NaN with PrecisionError. Malformed numeric strings raise ValueError. Unsupported Python objects can raise TypeError.

Type Minimum Maximum Decimal places
BoundedDecimal -999999999999999.99999 999999999999999.99999 5
NonNegativeAmount 0 No finite upper bound 2
PositiveAmount 0.01 999999999999999.99999 2
Percentage 0 1 6
Percentage100 0 100 6

String and Decimal inputs must fit the precision. Trailing zeros do not count toward precision. Float inputs round before validation, using the active decimal context. Thus NonNegativeAmount(1.234) succeeds but NonNegativeAmount("1.234") fails. Decimal context precision still limits quantization and arithmetic. Increase that precision for unusually large amounts. If quantization produces NaN with the InvalidOperation trap disabled, construction raises PrecisionError. With that trap enabled, insufficient context precision can raise decimal.InvalidOperation.

These are construction-only checks. Inherited arithmetic normally returns an unrestricted Decimal, not the original subtype. Percentage addition is the exception: the left-hand implementation constructs and validates the same percentage type. Inherited reverse addition and other operations still return Decimal. Percentage100.to_1() can fail if conversion needs more than six fractional places. For example, Percentage100("0.000001").to_1() raises PrecisionError; it does not round silently.

Countries and currencies

Country and Currency are str subclasses backed by the installed pycountry catalog. They require uppercase ASCII letters and exact ISO lengths: two for ISO 3166-1 countries, three for ISO 4217 currencies. They do not normalize input or restrict valid ISO codes. Malformed inputs raise CountryFormatError or CurrencyFormatError. Well-formed unknown codes raise CountryValueError or CurrencyValueError. The installed catalog determines the accepted codes. Native string operations can return ordinary strings outside these constraints.

Money

Money accepts finite Decimal, integer, and Decimal-compatible string amounts. It rejects floats. Numeric strings use a decimal point, never process-locale grouping or separators. Money validates its currency through Currency and allows zero and negative amounts. Its default rounding is ROUND_HALF_UP for every currency, including USD. Construction and arithmetic do not round the amount. round(money) uses its precision and rounding policy. Precision zero is supported. round(money, n) overrides the rounding scale for that operation, not its stored precision setting. Copies and arithmetic preserve explicit rounding. Addition, subtraction, and ordering require the same currency. Equality compares amount and currency. Locale, precision, and rounding do not affect equality. Money remains mutable and is deliberately unhashable. Attribute mutation can bypass constructor validation.

Localized formatting requires the formatting extra:

from finance_types import Money

assert str(Money("10", "USD", locale_name="en_US")) == "$10.00"

Without Babel, localized formatting raises an explicit ImportError. Construction, arithmetic, and repr() still work. Babel controls display conventions. Money controls rounding before that display step.

Django models and forms

from decimal import ROUND_HALF_EVEN
from django.db import models
from finance_types.django import CountryField, MoneyField, PercentageField

class Invoice(models.Model):
    country = CountryField()
    total = MoneyField(max_digits=12, decimal_places=2, rounding=ROUND_HALF_EVEN)
    tax_rate = PercentageField()

    class Meta:
        app_label = "billing"

MoneyField creates total_amount and total_currency columns, not a total column. Its DecimalField component accepts zero and negative amounts. Assignment rounds a copy of the supplied Money to the field's decimal_places and rounding policy:

from finance_types import Money

invoice = Invoice(total=Money("1.225", "USD", precision=3))
assert invoice.total.amount == Money("1.22", "USD").amount
assert invoice.total.precision == 2

Only amount and currency persist. Per-instance locale, precision, and rounding do not persist. Reads reconstruct the field's precision and rounding, with Money's default locale. Assigning None clears both components. Any null component makes the compound value None. Use null=True if the database must accept those null values.

kw_amount and kw_currency pass component options such as db_index, null, and blank. Set precision through MoneyField itself, not through kw_amount. The field preserves nondefault configuration in migrations. Direct component assignment, QuerySet.update(), and SQL bypass compound assignment normalization. Bulk operations persist the current component values; they do not repeat compound assignment normalization. Use the compound attribute to normalize Money, and call model validation before saving when input is untrusted. Django does not call full_clean() automatically during save(). Database enforcement depends on the backend.

AmountField(max_digits=11, decimal_places=2) is separate and retains positive-value validation. PercentageField represents 0 to 1. CurrencyField and CountryField validate their ISO scalar types. CountryFormField strips surrounding whitespace, preserves case, and validates the ISO country. CountryField selects that form field for ModelForm.

DRF serializers

from rest_framework import serializers
from finance_types.drf import CountrySerializer, Percentage100Serializer

class QuoteSerializer(serializers.Serializer):
    country = CountrySerializer()
    tax_percent = Percentage100Serializer()

quote = QuoteSerializer(data={"country": "IR", "tax_percent": "100"})
assert quote.is_valid(), quote.errors
assert quote.validated_data["tax_percent"] == 1
assert quote.data["tax_percent"] == "100.000000"

PercentageSerializer accepts and represents 0 to 1. Percentage100Serializer accepts 0 to 100, returns Percentage internally, and represents the 100 scale. Conversions must fit the core's six-place fractional precision; the adapter does not silently discard extra digits. Configured decimal_places counts significant fractional places, not zero padding added by the core. For example, PercentageSerializer(decimal_places=2, max_digits=3) accepts "0.1" but rejects "0.123". Float inputs retain the core's round-before-validation policy. Declare these fields explicitly on ModelSerializer too. This package does not change DRF's global field registry.

Supported versions

Requires Python 3.12 or newer. Django adapters support Django 5.2, 6.0, and 6.1. The drf extra requires djangorestframework>=3.16,<3.19. The test matrix uses two stack profiles:

Profile Python Django DRF
latest 3.15.2 6.1.3 3.18.3
lts 3.14.10 5.2.19 3.18.3

The lts profile selects Django's long-term support line. Python and DRF do not have equivalent LTS lines. Each profile runs five isolated environments: core, formatting, Django, DRF, and full. Core and formatting environments do not install Django, DRF, or django-typed-fields. Django environments exclude DRF and Babel. DRF environments exclude Babel. Full environments include Babel. Database tests use SQLite.

Testing and contributions

Install Python 3.14.10 and 3.15.2, plus tox 4.53.0 in a virtual environment. From a source checkout, run the complete matrix:

tox run

Tox builds and installs a wheel for each environment. Missing interpreters fail the run. It keeps environments, caches, and test databases outside the checkout. Set TOX_WORK_DIR to choose that directory (the default is /tmp/finance-types-tox). Use tox list to inspect the environments or tox run -e py315-full61-rest318 for the latest stack.

GitHub runs two compatibility jobs, one per profile. Each job runs all five environments through tox. Push and pull request jobs build the target wheel with tox. These jobs first fetch the public henriquebastos/django-typed-fields repository's main branch and record its commit SHA. They build that dependency in runner scratch space and constrain its installation to the resulting wheel. Core and formatting environments remain independent of that wheel. Release jobs use published dependencies and test the exact prebuilt release wheel without rebuilding it.

The tests check optional dependency isolation, installed package locations, README examples, and dependency consistency. Migration tests create and apply migrations, reconstruct historical models, check drift, reverse migrations, and apply them again. The finance test suite manages Django directly and does not use pytest-django.

For a bug report, include a minimal example and the Python, Django, and DRF versions involved. For a contribution, add a regression test and run the relevant tox environments before submitting a pull request. Contact Henrique Bastos at henrique@bastos.net for project questions.

Maintainer releases

Publish django-typed-fields first so that release tests can install its compatible version from PyPI. Set the version in pyproject.toml and publish a GitHub release tagged v{version}. The release workflow rejects prereleases and mismatched tags, builds distributions once, and tests that wheel across the full matrix.

To enable publication, register a PyPI Trusted Publisher and configure a protected GitHub environment with required approval. Set the repository variable PYPI_ENVIRONMENT to that environment and PYPI_PUBLISH_ENABLED to true. Only the publishing job receives an OIDC token. It publishes the tested wheel and source distribution without rebuilding them.

License

MIT. Copyright 2026 Henrique Bastos. See LICENSE.

Thank you to Routable

Routable sponsored the development of this library. Working at Routable is an awesome experience, with a developer-first culture that fosters innovation and growth. If you're interested in joining a dynamic team, check out our job opportunities here!

Authors

Metadata

Release files for finance-types 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for finance-types 0.1.0
File Size Uploaded Provenance Actions
finance_types-0.1.0.tar.gz 31.5 kB With provenance Details for finance_types-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for finance-types 0.1.0
File Interpreter ABI Platform Actions
finance_types-0.1.0-py3-none-any.whl Python 3 none any Details for finance_types-0.1.0-py3-none-any.whl

Total release size: 49.1 kB

Release files / finance_types-0.1.0.tar.gz

Download URL finance_types-0.1.0.tar.gz
Size 31.5 kB
Tags Source
SHA-256 checksum
How to use checksums
eeb45fd5be4d2dd762d9e5d339343223f47a8758a31d31542d6a8e94bf7ba0bf
BLAKE2b-256 checksum
How to use checksums
f64b1b31943476232217b1ce3ced1cb581126f2d4038d0b1cf0fd0bb03ccf551
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / finance_types-0.1.0-py3-none-any.whl

Download URL finance_types-0.1.0-py3-none-any.whl
Size 17.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
36784e8bf2f3aad616726ac8112f300a2cc206bdf2b0a8cdea0176f8e948606c
BLAKE2b-256 checksum
How to use checksums
37eed17bad32dff4ffb5049786d0bb0d78acd73bc722c0a0bf6b9349c545653a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for finance-types 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for finance_types-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page