Skip to main content

pydantic-stream-file

High-performance $O(1)$ RAM streaming file validation glue layer for Pydantic.

Python Pydantic Documentation License: MIT


📖 Documentation


⚡ Highlights

  • Strict $O(1)$ Memory Overhead: Memory consumption remains flat regardless of whether the file is 10 MB or 50 GB. Built for serverless (AWS Lambda) and container runtimes.
  • Fail-Safe & Dead Letter Queue (DLQ): A single corrupt row will not abort your pipeline. In YIELD_RESULT mode, errors are captured with raw payloads and exact file coordinates.
  • Delimiter & Multiline Cell Resilience: CsvAdapter handles any separator (,, ;, \t, |), preserves cells with internal \n enclosed in quotes, and coerces custom null sentinels ("", "NULL", "N/A").
  • Constant-Memory XML Streaming: XmlAdapter streams massive XML documents via iterparse, ruthlessly clearing subtrees and severing parent node references to prevent DOM accumulation.
  • Parent Context Extraction: Seamlessly extracts attributes from ancestor tags (e.g., batch_id from <orders batch_id="1">) and injects them into child models.
  • Vectorized Rust Batch Validation: Leverages compiled Rust batching (TypeAdapter(list[Model])) in pydantic-core, boosting throughput by up to 40%+ while isolating single-row errors.
  • Sync & Async Dualism: Drop-in identical APIs for blocking streams (StreamValidator) and async runtimes like FastAPI or S3 chunk downloads (StreamValidatorAsync).
  • Zero Heavy Runtime Dependencies: Core depends strictly on pydantic.

📦 Installation

pip install pydantic-stream-file

🚀 Quick Examples

1. Delimited Flat File (CSV) with Dead Letter Queue Routing

from typing import Optional
from pydantic import BaseModel
from pydantic_stream_file import StreamValidator, adapters, ErrorPolicy

class Transaction(BaseModel):
    id: int
    amount: float
    description: str
    notes: Optional[str] = None

# Initialize adapter with custom delimiter and null sentinels
csv_adapter = adapters.CsvAdapter(
    source="transactions.csv",  # or sys.stdin, open file handle, io.StringIO
    delimiter=",",
    null_values=["", "NULL", "N/A"]
)

# Connect validation engine
validator = StreamValidator(
    adapter=csv_adapter,
    model=Transaction,
    on_error=ErrorPolicy.YIELD_RESULT,
    batch_size=1000,
)

for result in validator:
    if result.is_valid:
        # Validated Pydantic model:
        save_clean_record(result.item)
    else:
        # Route to Dead Letter Queue:
        log_to_dlq(
            raw_payload=result.raw_data,
            error=result.error,
            location=result.location  # e.g., "Lines: 42-45 (Record: 40)"
        )

2. Constant-Memory XML Streaming with Parent Metadata

from pydantic import BaseModel
from pydantic_stream_file import StreamValidator, adapters

class Order(BaseModel):
    batch_id: str
    order_id: str
    amount: float

xml_adapter = adapters.XmlAdapter(
    source="massive_orders_50GB.xml",
    target_tag="order",
    context_tags=["orders"],  # extracts batch_id from <orders batch_id="...">
    attr_prefix="",
)

for order in StreamValidator(xml_adapter, Order, on_error="skip"):
    process(order)

3. Non-Blocking Async Streaming (FastAPI / aiobotocore)

from pydantic_stream_file import StreamValidatorAsync

async def process_stream(async_adapter, model):
    validator = StreamValidatorAsync(
        adapter=async_adapter,
        model=model,
        on_error="yield_result",
        batch_size=500
    )
    async for result in validator:
        if result.is_valid:
            await forward_to_kafka(result.item)
        else:
            await send_to_dlq(result.raw_data, result.error)

📑 Error Policies

Policy Behavior Return Type
ErrorPolicy.RAISE ("raise") Halts stream and raises ValidationError on first invalid record. Yields T
ErrorPolicy.SKIP ("skip") Silently drops invalid records. Yields T
ErrorPolicy.YIELD_RESULT ("yield_result") Never halts. Yields a StreamResult[T] for every record. Yields StreamResult[T]

🛠️ Running the Test Suite

python -m pytest tests

📄 License

MIT License. See LICENSE for details.

Release files for pydantic-stream-file 0.1.2

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

Source distribution (sdist)

Source distribution for pydantic-stream-file 0.1.2
File Size Uploaded
pydantic_stream_file-0.1.2.tar.gz 11.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-stream-file 0.1.2
File Interpreter ABI Platform
pydantic_stream_file-0.1.2-py3-none-any.whl Python 3 none any Details

Total release size: 23.1 kB

Release files / pydantic_stream_file-0.1.2.tar.gz

Download URL pydantic_stream_file-0.1.2.tar.gz
Size 11.5 kB
Tags Source
SHA-256 checksum
How to use checksums
3a3ec567a01ddd64b278767a04625c38bb6b66c587ca675ce89a107e5ed57e07
BLAKE2b-256 checksum
How to use checksums
e089a7582ba72bc44a685f723415f4327d2b28ce99b05708ad6f4a005021e836
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Sep 19, 2026.

Transparency log

Release files / pydantic_stream_file-0.1.2-py3-none-any.whl

Download URL pydantic_stream_file-0.1.2-py3-none-any.whl
Size 11.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c3d156dee3ac6a70d6fe786a7eabb5372c872fb509eb665672217625f0339b00
BLAKE2b-256 checksum
How to use checksums
d9b938989b14120aa620a6ee9b26b22188281dd73415caf028d737b70ae4c811
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Sep 19, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files

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