Models¶
The canonical data model is the typed boundary between the upstream
wire format and the consumer's view of the world. Every record is
immutable (frozen=True); monetary values are Decimal; dates are
ISO-8601 strings; enums are frozenset.
API reference¶
The full reference is generated from the SDK's docstrings via mkdocstrings.
models
¶
Metadata models for the UN Comtrade Python SDK.
This package provides frozen, validated dataclasses for
the canonical metadata entities described in
006_DATA_MODEL.md:
Country/Partner(E01)Classification(E02)HSCode(E04, HS-specialized commodity code)TradeFlow(E05)TransportMode(E06)Frequency(E09)
And the canonical trade-record models from §3.12 (P2-003):
Reporter(record-embedded)Partner(record-embedded; aliased toTradePartnerat the package level to avoid clashing with the catalogPartner)Commodity(record-embedded)TradeFlow(record-embedded; aliased toRecordTradeFlowat the package level)TradeValueQuantityTradeRecord
Per the task scope (P1-011 + P2-003) this module
contains models only: no transport, no metadata
download, no API integration. Validation is enforced
in __post_init__ per ADR-0013 and the documented
rules in the data-model specification.
Country
dataclass
¶
Bases: BaseModel
E01 Country — political entity.
Primary key: country_code (non-negative integer).
Validation per 006_DATA_MODEL.md §3.1.
Source code in un_comtrade/models/country.py
Partner
dataclass
¶
Bases: BaseModel
E01 Country in the partner role.
Distinct type from Country so dataclass equality
treats them separately — Country(699, ...) !=
Partner(699, ...). Shape and validation are
identical.
Source code in un_comtrade/models/country.py
Classification
dataclass
¶
Bases: BaseModel
E02 Classification — product classification system.
Primary key: classification_code (string).
Validation per 006_DATA_MODEL.md §3.2.
Source code in un_comtrade/models/classification.py
DataItem
dataclass
¶
Bases: BaseModel
A single reference-catalogue column / variable.
Primary key: data_item (string). Validation per the
upstream JSON shape (dataItem field).
Source code in un_comtrade/models/data_item.py
Frequency
dataclass
¶
Bases: BaseModel
E09 Frequency — time granularity of a query or record.
Primary key: frequency_code (string).
Validation per 006_DATA_MODEL.md §3.9.
Source code in un_comtrade/models/frequency.py
HSCode
dataclass
¶
Bases: BaseModel
E04 CommodityCode specialized to the HS classification.
Primary key (composite): (commodity_code,
classification_code, edition). Validation per
006_DATA_MODEL.md §3.4.
The model is specialized to HS in this task scope; future editions of the model MAY generalize to other classifications (SITC, BEC, EBOPS).
Source code in un_comtrade/models/hs_code.py
QuantityUnit
dataclass
¶
Bases: BaseModel
E08 QuantityUnit — unit of measurement for quantities.
Primary key: qty_unit_code (integer; -1 represents
the TOTAL / not-applicable aggregate). Validation per
006_DATA_MODEL.md §3.8.
Source code in un_comtrade/models/quantity_unit.py
ReferenceEntry
dataclass
¶
Bases: BaseModel
R01 row of the reference list.
Primary key: (category, variable) — both fields
together identify the row. Validation enforces
non-empty strings and a non-empty fileuri.
Source code in un_comtrade/models/reference_entry.py
TradeResponse
dataclass
¶
Bases: BaseModel
E22 Response — canonical success envelope.
Wraps the upstream's documented response shape:
elapsed_seconds— non-negative number.count— non-negative integer; per the data model contract this SHALL equal the number of records upstream reported (len(records)).records— list of canonicalTradeRecordinstances. Empty list when no records match. Distinct from the upstream'sdatafield; the canonical name isrecordsper PCR §10 ("canonical renamesdatatorecords").error— non-empty string on failure, empty string on success.upstream_url— the URL the request was sent to; useful for diagnostics and for consumers that want to replay the call.request— opaque request metadata (E21 payload) when the caller supplied one.skipped— number of records the parser dropped (validation failures or duplicates). Defaults to0when no parser ran.
Source code in un_comtrade/models/response.py
Commodity
dataclass
¶
Bases: BaseModel
Commodity as it appears on a trade record.
commodity_code is the HS code (2/4/6 digits) or a
tariffline extension (8/10 digits), or "TOTAL"
(the wildcard that selects every commodity). The
display name is optional because the upstream
returns null when includeDesc=false.
Source code in un_comtrade/models/trade.py
TradePartner
dataclass
¶
Bases: BaseModel
Partner as it appears on a trade record.
partner_code=0 with iso3="W00" and name="World"
is the documented sentinel for the World aggregate
(PCR Q13, 006_DATA_MODEL.md §4.12). The model
accepts any non-negative int but does NOT enforce
that the World sentinel is paired with the matching
iso3/name — that is the upstream's responsibility.
Source code in un_comtrade/models/trade.py
Quantity
dataclass
¶
Bases: BaseModel
Quantity section of a trade record.
Carries the primary quantity, the alternate quantity
(when reported by the upstream), and their unit codes
/ abbreviations. All numeric values are Decimal.
The unit code -1 is the documented "no unit"
sentinel and is accepted as-is (PCR Q28).
Estimation flags default to False because the
upstream omits the field when the value is exact.
Source code in un_comtrade/models/trade.py
Reporter
dataclass
¶
Bases: BaseModel
Reporter as it appears on a trade record.
Smaller than the catalog Country model: only the
code, ISO alpha-3 code (if provided), and display
name. No effective dates, no entry metadata.
reporter_code is the upstream's reporterCode
integer (e.g. 699 for India).
Source code in un_comtrade/models/trade.py
RecordTradeFlow
dataclass
¶
Bases: BaseModel
Trade flow as it appears on a trade record.
Distinct from the catalog TradeFlow model in
models/trade_flow.py: the record-embedded variant
carries only the code and display name, no taxonomy
metadata.
flow_code must be one of M / X / RX / RM.
Source code in un_comtrade/models/trade.py
TradeRecord
dataclass
¶
Bases: BaseModel
E12 TradeRecord — a single trade observation.
Composes the record-embedded dimension models (Reporter / Partner / Commodity / TradeFlow) and the value-bearing sub-models (TradeValue / Quantity) with the upstream's metadata fields. Frozen and validated.
Validation rules enforced (per 006_DATA_MODEL.md §4.12):
type_code∈{"C", "S"}.frequency_code∈{"A", "M"}.ref_yearin 1900..2100.ref_monthin {1..12, 52} (52 = annual).periodmatchesYYYYorYYYYMM.classification_code,edition,period,customs_code,mos_codeare non-empty strings.mot_codeis a non-negative int.legacy_estimation_flagis a non-negative int.net_weight_kg,gross_weight_kgare non-negative Decimals (or None).
Source code in un_comtrade/models/trade.py
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 | |
TradeValue
dataclass
¶
Bases: BaseModel
Monetary value triplet for a trade record.
All values are USD (per 006_DATA_MODEL.md §4.12)
and use Decimal for exact arithmetic. The
upstream may return null for cif_value and
fob_value (when not applicable to the flow
direction); primary_value is required.
Per 006_DATA_MODEL.md §3.12, all values SHALL be
non-negative when present.
Source code in un_comtrade/models/trade.py
TradeFlow
dataclass
¶
Bases: BaseModel
E05 TradeFlow — direction of a trade.
Primary key: flow_code (string).
Validation per 006_DATA_MODEL.md §3.5.
Source code in un_comtrade/models/trade_flow.py
TransportMode
dataclass
¶
Bases: BaseModel
E06 TransportMode — mode of transport.
Primary key: mot_code (integer; 0 represents the
TOTAL aggregate). Validation per 006_DATA_MODEL.md
§3.6.
Source code in un_comtrade/models/transport_mode.py
config
¶
Configuration subsystem for the UN Comtrade Python SDK.
This module owns the configuration contract declared in
007_SDK_SPECIFICATION.md §8 and the configuration strategy in
010_INFRASTRUCTURE_SPECIFICATION.md §3.
The configuration is:
- a typed, immutable object (@dataclass(frozen=True))
- loaded from one or more sources in priority order:
1. explicit construction argument
2. environment variable
3. default value
- validated at construction; invalid values raise ConfigurationError
- never mutated after construction
No HTTP, transport, retry, timeout, logging, or business logic lives in this module.
ConfigurationError
¶
Bases: ComtradeError, ValueError
Raised when the configuration is invalid at construction time.
Per 010_INFRASTRUCTURE_SPECIFICATION.md §3.5, the configuration
is validated at construction. An invalid configuration raises
ConfigurationError before the first call is issued.
Source code in un_comtrade/exceptions.py
Configuration
dataclass
¶
Immutable SDK configuration.
Per 007_SDK_SPECIFICATION.md §8 and
010_INFRASTRUCTURE_SPECIFICATION.md §3.
Source code in un_comtrade/config.py
load_configuration
¶
load_configuration(
*,
api_key: str | None = None,
base_url: str | None = None,
user_agent: str | None = None,
timeout_seconds: float | None = None,
metadata_timeout_seconds: float | None = None,
download_timeout_seconds: float | None = None,
max_retries: int | None = None,
initial_backoff_seconds: float | None = None,
backoff_multiplier: float | None = None,
backoff_cap_seconds: float | None = None,
proxy_url: str | None = None,
cache_enabled: bool | None = None,
cache_directory: str | Path | None = None,
metadata_cache_ttl_seconds: int | None = None,
trade_cache_ttl_seconds: int | None = None,
log_level: str | None = None,
log_format: str | None = None,
env: Mapping[str, str] | None = None,
) -> Configuration
Build a Configuration from explicit kwargs, environment, defaults.
Resolution priority (highest first):
1. Explicit kwargs passed to this function.
2. Environment variables (configurable via the env mapping,
defaulting to os.environ).
3. Built-in defaults documented in the specifications.
The env parameter is provided for testability; production code
should let it default to os.environ.
No I/O is performed; no network or filesystem access occurs.
Source code in un_comtrade/config.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
Examples¶
from un_comtrade import ComtradeClient
from un_comtrade.config import Configuration
config = Configuration(api_key="your-key", retry_attempts=3)
with ComtradeClient(config) as client:
exports = client.trade.get_exports(reporter_code=699, period="2022")
record = exports.records[0]
print(record.primary_value, record.partner_code, record.flow_code)
Related Recipes¶
- RECIPE-001 — List reporter countries.
Related Guides¶
- Python SDK → Index — idiomatic patterns.