Skip to main content

Shims for pydantic 1 to use syntax like pydantic 2.

Project description

pydantic-12-shims

A compatibility layer that lets you write Pydantic v2-style code that works with both Pydantic v1 and v2.

Problem

Pydantic v2 introduced significant API changes, outlined in their migration guide. Key changes include:

Pydantic v1 Pydantic v2
.parse_obj() .model_validate()
.dict() .model_dump()
.json() .model_dump_json()
class Config model_config = ConfigDict(...)
@validator @field_validator
@root_validator @model_validator

This library provides shims so you can write v2-style code that runs on both versions.

Why use this library?

In a heterogeneous environment where some projects use Pydantic v1 and others v2, this library lets you maintain a single codebase with v2-style syntax. You can incrementally migrate while still on pydantic<2 — ideally, the final change is just updating a pyproject.toml. Once all services use Pydantic v2, you can replace pydantic_12_shims imports with direct Pydantic v2 imports.

Pydantic v2 provides the pydantic.v1 module for this purpose, but pydantic.v1.BaseModel is not interoperable with native v2 BaseModel. For example, using a pydantic.v1 model as a field type in a native v2 model raises a TypeError:

# module1.py is still stuck on pydantic.v1:
from pydantic.v1 import BaseModel as V1BaseModel, Field

class MyLegacyModel(V1BaseModel):
    name: str = Field(default="legacy")


# module2.py wants to use native v2 models:
from pydantic import BaseModel
from module1 import MyLegacyModel

class ShinyNewModel(BaseModel):
    legacy_value: MyLegacyModel
    # TypeError: BaseModel.validate() takes 2 positional arguments but 3 were given

This led major libraries like FastAPI to drop pydantic.v1 support entirely, making it an unviable migration path.

Installation

pip install pydantic-12-shims

Usage

Replace your Pydantic imports with imports from this library:

# Instead of:
# from pydantic import BaseModel, Field, field_validator, model_validator, ConfigDict

# Use:
from pydantic_12_shims import BaseModel, Field, field_validator, model_validator, ConfigDict

Then write your models using Pydantic v2 syntax:

from pydantic_12_shims import BaseModel, ConfigDict, Field, field_validator, model_validator

class User(BaseModel):
    model_config = ConfigDict(frozen=True, populate_by_name=True)

    name: str = Field(min_length=1)
    email: str
    age: int = Field(ge=0)

    @field_validator("email")
    @classmethod
    def validate_email(cls, v: str) -> str:
        if "@" not in v:
            raise ValueError("Invalid email")
        return v.lower()

    @model_validator(mode="after")
    def validate_model(self):
        # validation logic
        return self

# Use v2-style methods
user = User.model_validate({"name": "Alice", "email": "ALICE@example.com", "age": 30})
data = user.model_dump()
json_str = user.model_dump_json()

This code works identically whether Pydantic v1 or v2 is installed.

API Reference

Exports

  • BaseModel - Base class for models with v2-style methods
  • ConfigDict - Configuration dictionary (v2 style)
  • Field - Field definition with v2 parameter names
  • field_validator - Field validator decorator (v2 style)
  • model_validator - Model validator decorator (v2 style)
  • GenericModel - Base class for generic models
  • ValidationError - Validation exception
  • PrivateAttr - Private attribute marker
  • PYDANTIC1 / PYDANTIC2 - Booleans indicating which major version is installed

Validators

field_validator:

@field_validator("field_name", mode="before")  # or mode="after"
@classmethod
def validate_field(cls, v):
    return v

model_validator:

@model_validator(mode="before")  # receives dict
@classmethod
def validate_before(cls, values: dict) -> dict:
    return values

@model_validator(mode="after")  # receives model instance
def validate_after(self):
    return self

Note: support for validators is partial, e.g. the handler and info arguments are not yet supported.

Generic Models

For generic models, use GenericModel:

from typing import Generic, TypeVar
from pydantic_12_shims import GenericModel

T = TypeVar("T")

class Container(GenericModel, Generic[T]):
    value: T

# Parameterize the generic
IntContainer = Container[int]
instance = IntContainer(value=42)

Migrating off pydantic.v1

If your codebase uses Pydantic v2's pydantic.v1 compatibility module and you want to migrate away from it:

# Instead of:
# from pydantic.v1 import BaseModel

# Use:
from pydantic_12_shims.v1 import BaseModel

On Pydantic v2, pydantic_12_shims.v1 wraps pydantic.v1 models to be interoperable with native v2 BaseModel. Once every pydantic.v1 import has been replaced, set the environment variable TURN_PYDANTIC_V1_OFF=true to switch to native v2 models entirely — this lets you verify the migration works before removing the shim imports.

Version Detection

from pydantic_12_shims import PYDANTIC1, PYDANTIC2

if PYDANTIC1:
    # Pydantic v1 specific code
    pass

if PYDANTIC2:
    # Pydantic v2 specific code
    pass

License

See LICENSE file.

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

pydantic_12_shims-0.0.1.tar.gz (22.2 kB view details)

Uploaded Source

Built Distribution

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

pydantic_12_shims-0.0.1-py3-none-any.whl (14.5 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_12_shims-0.0.1.tar.gz.

File metadata

  • Download URL: pydantic_12_shims-0.0.1.tar.gz
  • Upload date:
  • Size: 22.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pydantic_12_shims-0.0.1.tar.gz
Algorithm Hash digest
SHA256 d27ed4155f1760171b04be5e447846c03c7172d3eb280f293b5d5106917189d0
MD5 5182f0b76adc9d2f31adf62274acf4f5
BLAKE2b-256 f502df872fc3f47e298361dd18bb79baca38a6eea3e4091eae9a11d0b0904364

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_12_shims-0.0.1.tar.gz:

Publisher: publish.yml on akasa-opensource/pydantic-12-shims

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pydantic_12_shims-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_12_shims-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 92a5d7589b2ec61ada3fddff666a00259a763abc345e4edc48f833f583e492c7
MD5 34fa18135c400c1c6069b6a7e231a173
BLAKE2b-256 a36cc9752c729b7c3ec726e377f32d059de23e71ec8aa8104081a3bd410d1364

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_12_shims-0.0.1-py3-none-any.whl:

Publisher: publish.yml on akasa-opensource/pydantic-12-shims

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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