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
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 formatsDateDMYSerializerMixin: Specialized mixin for DD/MM/YYYY formatDateNumberSerializerMixin: 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:
- Detect all date fields automatically
- Validate and convert string inputs to date objects
- Serialize date objects to strings in the specified format
- Override the
model_dumpmethod to ensure consistent formatting
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file karpyncho_pydantic_extensions-0.2.0.tar.gz.
File metadata
- Download URL: karpyncho_pydantic_extensions-0.2.0.tar.gz
- Upload date:
- Size: 6.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1650728430aa4cf0fdb79854ce8c4596054695622998b076350cfb797c85901f
|
|
| MD5 |
3debb70e1c76be26d85ab7052aa8ca39
|
|
| BLAKE2b-256 |
5485dc4b984968e64c25563ff6111f55039b8ad9bb61e57b58068b3d2bda3af1
|
File details
Details for the file karpyncho_pydantic_extensions-0.2.0-py3-none-any.whl.
File metadata
- Download URL: karpyncho_pydantic_extensions-0.2.0-py3-none-any.whl
- Upload date:
- Size: 7.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
24924b3262b4f935ebb73359192eedd3d4e4c72a88117d3ba9410fe522593167
|
|
| MD5 |
f0ac42b46903522f26a1b6c407fce7af
|
|
| BLAKE2b-256 |
4109ae0e12c5fa65e5eb39976de730fa8fc222fd9fd303aba35bb99babf4d6cf
|