Skip to main content

A collection of extensions and enhancements for the Pydantic library, providing custom mixins and utilities to enhance your data validation and serialization capabilities.

Project description

Karpyncho Pydantic Extensions

PyPI version PyPI version

Python versions

check codecov GitHub License

Goal

A collection of extensions and enhancements for the Pydantic library, providing custom mixins and utilities to enhance your data validation and serialization capabilities.

Features

  • Date Serialization: Custom mixins for consistent date handling with configurable formats
    • DateSerializerMixin: Generic mixin for customizable date formats
    • DateDMYSerializerMixin: Specialized mixin for DD/MM/YYYY format
    • DateNumberSerializerMixin: Specialized mixin for YYYYMMDD format, serialized as an integer value instead of string

Installation

pip install pydantic-extensions

Usage

Basic Usage with DateSerializerMixin

The DateSerializerMixin provides a generic solution for handling date serialization with a customizable format:

from datetime import date
from pydantic import BaseModel
from karpyncho.pydantic_extensions import DateSerializerMixin

class Person(DateSerializerMixin, BaseModel):
    name: str
    birth_date: date
    
# The date will be formatted as YYYY-MM-DD (default format)
person = Person(name="John Doe", birth_date="2000-01-21")
print(person.model_dump())  # {'name': 'John Doe', 'birth_date': '2000-01-21'}

# You can also use date objects directly
person = Person(name="John Doe", birth_date=date(2000, 1, 21))
print(person.model_dump())  # {'name': 'John Doe', 'birth_date': '2000-01-21'}

# You can also deserialize a JSON string
json_str = '{"name": "John Doe", "birth_date": "2000-01-21"}'
person_dict = Person.loads(json_str)
person = Person(**person_dict)  
print(person)  # {'name': 'John Doe', 'birth_date': '2000-01-21'}

Using DateDMYSerializerMixin for DD/MM/YYYY Format

For European date format (DD/MM/YYYY), use the specialized mixin:

from datetime import date
from pydantic import BaseModel
from karpyncho.pydantic_extensions import DateDMYSerializerMixin

class Person(DateDMYSerializerMixin, BaseModel):
    name: str
    birth_date: date
    
# The date will be formatted as DD/MM/YYYY
person = Person(name="John Doe", birth_date="21/01/2000")
print(person.model_dump())  # {'name': 'John Doe', 'birth_date': '21/01/2000'}

# You can also provide dates in different formats during initialization
person = Person(name="John Doe", birth_date=date(2000, 1, 21))
print(person.model_dump())  # {'name': 'John Doe', 'birth_date': '21/01/2000'}

# You can also deserialize a JSON string
json_str = '{"name": "John Doe", "birth_date": "21/01/2000"}'
person_dict = Person.loads(json_str)
person = Person(**person_dict)  
print(person)  # {'name': 'John Doe', 'birth_date': '21/01/2000'}

Creating Custom Date Format Mixins

You can create your own date format mixins by inheriting from DateSerializerMixin:

from karpyncho.pydantic_extensions import DateSerializerMixin
from typing import ClassVar

class DateMDYSerializerMixin(DateSerializerMixin):
    """American-style date format (MM/DD/YYYY)"""
    __date_format__: ClassVar[str] = "%m/%d/%Y"

Advanced Usage

Multiple Date Fields

The mixins automatically handle all date fields in your model:

from datetime import date
from pydantic import BaseModel
from karpyncho.pydantic_extensions import DateDMYSerializerMixin

class Event(DateDMYSerializerMixin, BaseModel):
    title: str
    start_date: date
    end_date: date
    
event = Event(
    title="Conference",
    start_date="01/06/2023",
    end_date="05/06/2023"
)

print(event.model_dump())
# {'title': 'Conference', 'start_date': '01/06/2023', 'end_date': '05/06/2023'}

Error Handling

The mixins include validation to ensure dates are provided in the correct format:

from datetime import date
from pydantic import BaseModel
from karpyncho.pydantic_extensions import DateDMYSerializerMixin

class Person(DateDMYSerializerMixin, BaseModel):
    name: str
    birth_date: date
    
# This will raise a validation error
try:
    person = Person(name="John Doe", birth_date="2000-01-01")  # Wrong format
except ValueError as e:
    print(f"Error: {e}")  # Error: Date must be in %d/%m/%Y format

How It Works

The mixins utilize Pydantic's initialization hooks and field validators to:

  1. Detect all date fields automatically
  2. Validate and convert string inputs to date objects
  3. Serialize date objects to strings in the specified format
  4. Override the model_dump method to ensure consistent formatting

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

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

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

karpyncho_pydantic_extensions-0.2.0.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

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

File details

Details for the file karpyncho_pydantic_extensions-0.2.0.tar.gz.

File metadata

File hashes

Hashes for karpyncho_pydantic_extensions-0.2.0.tar.gz
Algorithm Hash digest
SHA256 1650728430aa4cf0fdb79854ce8c4596054695622998b076350cfb797c85901f
MD5 3debb70e1c76be26d85ab7052aa8ca39
BLAKE2b-256 5485dc4b984968e64c25563ff6111f55039b8ad9bb61e57b58068b3d2bda3af1

See more details on using hashes here.

File details

Details for the file karpyncho_pydantic_extensions-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for karpyncho_pydantic_extensions-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 24924b3262b4f935ebb73359192eedd3d4e4c72a88117d3ba9410fe522593167
MD5 f0ac42b46903522f26a1b6c407fce7af
BLAKE2b-256 4109ae0e12c5fa65e5eb39976de730fa8fc222fd9fd303aba35bb99babf4d6cf

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