Skip to content

airth-solutions/pydantic-unece-units

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pydantic-unece-units

CI PyPI version Python versions License: MIT Ruff Type checked: mypy

A Python library for validating UNECE Recommendation 20 unit codes with Pydantic v2.

What is UNECE Rec 20?

UNECE Recommendation 20 defines standard codes for units of measure used in international trade. Examples include:

  • KGM - kilogram
  • MTR - metre
  • LTR - litre
  • PCE - piece

This library provides 2,136 unit codes from Revision 17 (2021), the latest revision.

Installation

pip install pydantic-unece-units

Quick Start

Pydantic Model Validation

from pydantic import BaseModel
from pydantic_unece_units import UnitCode

class Product(BaseModel):
    name: str
    quantity: float
    uom: UnitCode  # Unit of Measure

# Valid codes are accepted
product = Product(name="Steel", quantity=100, uom="KGM")
print(product.uom.name)    # "kilogram"
print(product.uom.symbol)  # "kg"

# Serializes back to code string
print(product.model_dump())  # {"name": "Steel", "quantity": 100, "uom": "KGM"}

# Invalid codes raise ValidationError
Product(name="Steel", quantity=100, uom="INVALID")  # ValidationError

Restricting to Specific Units

Use RestrictTo to limit which unit codes are allowed:

from typing import Annotated
from pydantic import BaseModel
from pydantic_unece_units import UnitCode, RestrictTo

# Define reusable restricted types
WeightUnit = Annotated[UnitCode, RestrictTo("KGM", "LBR", "ONZ", "GRM")]
VolumeUnit = Annotated[UnitCode, RestrictTo("LTR", "MLT", "GLL")]

class Product(BaseModel):
    weight: float
    weight_uom: WeightUnit
    volume: float
    volume_uom: VolumeUnit

# Valid - KGM is in the allowed list
product = Product(weight=5.0, weight_uom="KGM", volume=1.0, volume_uom="LTR")

# ValidationError - MTR is not in WeightUnit's allowed codes
Product(weight=5.0, weight_uom="MTR", volume=1.0, volume_uom="LTR")

Invalid codes in RestrictTo raise ValueError at definition time:

RestrictTo("KGM", "INVALID")  # ValueError: 'INVALID' is not a valid UNECE Rec 20 code

The generated JSON Schema includes an enum constraint:

{"type": "string", "enum": ["GRM", "KGM", "LBR", "ONZ"]}

Direct Usage

from pydantic_unece_units import Rec20UnitCode

# Get unit (raises ValueError if invalid)
unit = Rec20UnitCode.from_code("KGM")
print(unit.name)        # "kilogram"
print(unit.symbol)      # "kg"
print(unit.common_code) # "KGM"

# Get unit (returns None if invalid)
unit = Rec20UnitCode.get("KGM")

# Check if valid
Rec20UnitCode.is_valid("KGM")  # True
Rec20UnitCode.is_valid("XXX")  # False

API Reference

UnitCode

Pydantic annotated type for use in models. Accepts string codes, validates against UNECE Rec 20, and serializes back to string.

RestrictTo

Annotation constraint to limit UnitCode to specific allowed codes. Use with Annotated[UnitCode, RestrictTo(...)]. Validates codes at definition time and generates JSON Schema with enum constraint.

Rec20UnitCode

The underlying Pydantic model with these fields:

Field Type Description
common_code str 2-3 character UN/CEFACT code
name str Official unit name
symbol str | None Standard symbol (e.g., "kg")

Class methods:

Method Returns Description
from_code(code) Rec20UnitCode Get unit, raises ValueError if invalid
get(code) Rec20UnitCode | None Get unit, returns None if invalid
is_valid(code) bool Check if code is valid

Data Source

Unit codes are sourced from:

Requirements

  • Python 3.10+
  • Pydantic 2.9+

License

MIT

Links

About

Pydantic-based validation for UNECE Recommendation 20 unit codes

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages