Skip to main content

Convert YAML schemas to Pydantic models

Project description

๐Ÿงฌ yaml2pydantic

PyPI version codecov Documentation Python Version License: MIT

A powerful, extensible schema compiler that turns YAML/JSON definitions into dynamic Pydantic models โ€” with full support for:

  • โœ… Custom types
  • โœ… Field and model-level validators
  • โœ… Custom serializers (field- and model-level)
  • โœ… Default values
  • โœ… Nested models
  • โœ… Reusable shared components
  • โœ… Auto-importing of components
  • โœ… Built-in type system

๐Ÿ“š View the full documentation

Built for teams that want to define models declaratively in YAML but leverage all the power of Pydantic v2.


โœจ Key Features

Feature Description
๐Ÿ“„ YAML/JSON to Pydantic Define your models in YAML or JSON, and compile them into Pydantic models.
๐Ÿงฑ Custom Types Extend your schema with types like Money, MonthYear, etc.
๐Ÿงช Validators Use reusable or model-specific validators (check_positive, etc.)
๐ŸŽจ Serializers Serialize fields or models however you want (Money โ†’ "R$ 10,00")
๐Ÿ” Field Defaults Fully supports defaults for primitive and complex types
โš™๏ธ Dynamic ModelFactory All logic for building Pydantic models is centralized and pluggable
๐Ÿ“š Registry-based architecture Types, validators, serializers all managed through shared registries
๐Ÿ”„ Auto-importing Components are automatically imported from components directory
๐Ÿ—๏ธ Built-in Types Support for common types like Money, MonthYear, and all Pydantic primitives

๐Ÿš€ Quick Start (For Users)

Installation

pip install yaml2pydantic

Basic Usage

  1. Define your model in YAML:
# models/user.yaml
User:
  fields:
    name:
      type: str
      max_length: 10
    age:
      type: int
      ge: 0
    email:
      type: Optional[str]
      default: null
  1. Use it in your Python code:
from yaml2pydantic import ModelFactory

# Load and compile the model
factory = ModelFactory()
User = factory.create_model("User", "models/user.yaml")

# Use it like any Pydantic model
user = User(
    name="John Doe",
    age=30,
    email="john@example.com"
)

Advanced Usage Example

Here's a more comprehensive example showing the full power of yaml2pydantic:

# models/user.yaml
User:
  fields:
    name:
      type: str
      max_length: 10  # Built-in Pydantic field constraints
    age:
      type: int
      ge: 0          # Built-in Pydantic field constraints
      validators:
        - check_positive  # Custom validator
    email:
      type: Optional[str]
      default: null
    birthday:
      type: datetime
    address:
      type: Address
      default:
        street: "Unknown"
        city: "Unknown"
        zip: "00000"
    balance:
      type: Money
      default: 0
      serializers:
        - money_as_string  # Custom serializer
    start_date:
      type: MonthYear
      default: "03/2025"

Address:
  fields:
    street:
      type: str
    city:
      type: str
    zip:
      type: str
      pattern: "^[0-9]{5}(-[0-9]{4})?$"
from yaml2pydantic import ModelFactory

# Load and compile the model
factory = ModelFactory()
User = factory.create_model("User", "models/user.yaml")

# Use it like any Pydantic model
user = User(
    name="John Doe",
    age=30,
    email="john@example.com",
    birthday="1990-01-01",
    address={
        "street": "123 Main St",
        "city": "Anytown",
        "zip": "12345"
    },
    balance=1000,
    start_date="03/2025"
)

Advanced Features


๐Ÿ› ๏ธ Development Guide (For Contributors)

Project Setup

# Clone the repository
git clone https://github.com/banduk/yaml2pydantic.git
cd yaml2pydantic

# Set up the development environment
make setup

# Activate the virtual environment
source .venv/bin/activate

Project Structure

yaml2pydantic/
โ”œโ”€โ”€ main.py                       # Entry point to load + test models
โ”œโ”€โ”€ models/                       # YAML/JSON model definitions
โ”‚   โ””โ”€โ”€ user.yaml
โ”œโ”€โ”€ components/                   # Shared reusable logic
โ”‚   โ”œโ”€โ”€ serializers/              # Custom serialization functions
โ”‚   โ”‚   โ””โ”€โ”€ money.py              # Money-specific serializers
โ”‚   โ”œโ”€โ”€ types/                    # Custom types (Money, MonthYear)
โ”‚   โ”‚   โ”œโ”€โ”€ money.py              # Money type implementation
โ”‚   โ”‚   โ””โ”€โ”€ monthyear.py          # MonthYear type implementation
โ”‚   โ””โ”€โ”€ validators/               # Custom validation logic
โ”‚       โ”œโ”€โ”€ email.py              # Email-related validators
โ”‚       โ””โ”€โ”€ numeric.py            # Numeric validators
โ””โ”€โ”€ core/                         # Core schema engine
    โ”œโ”€โ”€ factory.py                # ModelFactory that builds Pydantic models
    โ”œโ”€โ”€ loader.py                 # Loads YAML, JSON, or dict input
    โ”œโ”€โ”€ registry.py               # Shared registries for types, validators, serializers
    โ”œโ”€โ”€ types.py                  # TypeRegistry
    โ”œโ”€โ”€ validators.py             # ValidatorRegistry
    โ””โ”€โ”€ serializers.py            # SerializerRegistry

Development Workflow

  1. Create a new feature branch:

    git checkout -b feature/your-feature-name
    
  2. Make your changes and run tests:

    make test
    
  3. Run code quality checks:

    make lint
    make format
    python -m mypy .
    
  4. Update documentation:

    make docs
    
  5. Submit a pull request

Testing

# Run all tests
make test

# Run tests with coverage
python -m pytest --cov=yaml2pydantic

Documentation

# Build the documentation
make docs

# View the documentation
make docs-serve

Code Quality

# Run the linter
make lint

# Format the code
make format

# Type check
make type-check

# Security check
make security-check

Or just run

make all-checks

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿค Contributing

We welcome contributions! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.


๐Ÿ“š Documentation

For detailed documentation, visit our documentation site.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

yaml2pydantic-0.1.0.tar.gz (12.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

yaml2pydantic-0.1.0-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file yaml2pydantic-0.1.0.tar.gz.

File metadata

  • Download URL: yaml2pydantic-0.1.0.tar.gz
  • Upload date:
  • Size: 12.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.12

File hashes

Hashes for yaml2pydantic-0.1.0.tar.gz
Algorithm Hash digest
SHA256 cec80f4a4abd7fb4485e682e5ac1dd7b597f3fa64401fbac725e30dbc74fe31f
MD5 ab4213d5beafa9f92f05b076dee71e57
BLAKE2b-256 60af9a0e8b3572ab41b16ce79620b8f3b94efe8926c4a9770c510570bb3edfae

See more details on using hashes here.

File details

Details for the file yaml2pydantic-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: yaml2pydantic-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.12

File hashes

Hashes for yaml2pydantic-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 aebc1312ad6b0b97230b9a47bf04f10e691244eb9e58ffd4c8b1f5be17e642f3
MD5 3db31c2a167dace42fd52ca805c253ff
BLAKE2b-256 559510c53a072fd7f76841cb4951456e2b6abe0995d7fa6b6c2d4d56d02781c0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page