Skip to content

Instantly share code, notes, and snippets.

@bbelderbos
Created June 19, 2026 10:00
Show Gist options
  • Select an option

  • Save bbelderbos/76accc6e4107c1dcd2b3e7364fef7897 to your computer and use it in GitHub Desktop.

Select an option

Save bbelderbos/76accc6e4107c1dcd2b3e7364fef7897 to your computer and use it in GitHub Desktop.
from decimal import Decimal
from pydantic import BaseModel, ValidationError
class Expense(BaseModel):
amount: Decimal
# coercion: each valid input becomes a Decimal
for v in [5, 5.50, "5.50", Decimal("5.50")]:
got = Expense(amount=v).amount
print(f"{v!r:18} -> {got!r:18} (type={type(got).__name__})")
print("-" * 55)
# rejection: anything that isn't a number
for v in ["abc", None, [5]]:
try:
Expense(amount=v)
print(f"{v!r:18} -> accepted (unexpected)")
except ValidationError as e:
print(f"{v!r:18} -> rejected: {e.errors()[0]['msg']}")
"""
output:
5 -> Decimal('5') (type=Decimal)
5.5 -> Decimal('5.5') (type=Decimal)
'5.50' -> Decimal('5.50') (type=Decimal)
Decimal('5.50') -> Decimal('5.50') (type=Decimal)
-------------------------------------------------------
'abc' -> rejected: Input should be a valid decimal
None -> rejected: Decimal input should be an integer, float, string or Decimal object
[5] -> rejected: Decimal input should be an integer, float, string or Decimal object
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment