Skip to content

Add Decimal support to json and pyyaml preconf converters#764

Open
Binilkks wants to merge 1 commit into
python-attrs:mainfrom
Binilkks:fix/decimal-preconf-support
Open

Add Decimal support to json and pyyaml preconf converters#764
Binilkks wants to merge 1 commit into
python-attrs:mainfrom
Binilkks:fix/decimal-preconf-support

Conversation

@Binilkks

Copy link
Copy Markdown

Closes #761

Summary

  • Registers Decimal unstructure/structure hooks in preconf/json.py and preconf/pyyaml.py
  • Decimals are serialized as strings to avoid the float precision loss that json.dumps(float(Decimal("19.99"))) causes
  • pyyaml hook uses Decimal(str(v)) so that values YAML auto-parses as floats are still re-converted correctly
  • Adds 3 new tests in tests/test_preconf.py: round-trip, precision preservation, and dumps/loads integration

Behaviour

from decimal import Decimal
from attrs import define
from cattrs.preconf.json import make_converter

@define
class Order:
    amount: Decimal

converter = make_converter()
order = Order(amount=Decimal("19.99"))

data = converter.unstructure(order)   # {"amount": "19.99"}  ← string, not float
assert data["amount"] == "19.99"

restored = converter.structure(data, Order)
assert restored == order              # exact Decimal equality

Test plan

  • test_decimal_round_trip — verifies string representation and round-trip equality for both json and pyyaml converters
  • test_decimal_precision_preserved_json0.1 + 0.2 round-trips without float precision loss
  • test_decimal_json_dumps_loads — end-to-end dumps/loads with multiple Decimal fields

🤖 Generated with Claude Code

…hon-attrs#761)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@Tinche

Tinche commented Jun 28, 2026

Copy link
Copy Markdown
Member

I think this is a good change. Can we also apply it to the rest of the json preconfs? Ujson, orjson and msgspec. Note that some of them may already be doing the right thing, in which case we should let them handle it by default.

@codspeed-hq

codspeed-hq Bot commented Jun 28, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 64 untouched benchmarks


Comparing Binilkks:fix/decimal-preconf-support (8c04cdb) with main (3d07082)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (f47bbe0) during the generation of this report, so 3d07082 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

decimal.Decimal not handled in preconf converters (json, pyyaml)

2 participants