Skip to main content

Subclass driven extensible validation for pydantic

Project description

pydantic-magic is an extension of pydantic which provides validation-time delegation to model subclasses through a new base model class MagicModel. Functionally, the behavior is similar to pydantic's discriminated union but as any imported subclass can be targeted, models can refer to only the expected base type while remaining fully extensible.

from math import pi

from pydantic_magic import MagicModel

class Shape(MagicModel, abstract=True):
    def area(self) -> float:
        raise NotImplementedError

class Circle(Shape):
    radius: float

    def area(self) -> float:
        return pi * self.radius ** 2

class Square(Shape):
    side: float

    def area(self) -> float:
        return self.side ** 2

print(Shape.model_validate({"type": "circle", "radius": 5.0}).area())

NamedMagicModel extends this idea further by allowing model instances to be named and referenced by name during validation. When validating nested MagicModel types, any NamedMagicModel instance has its name registered to the parent validation frame so any sibling models can refer to it without duplication or an additional transformation layer.

from pydantic_magic import MagicModel, NamedMagicModel

class Worker(NamedMagicModel, abstract=True):
    pass

class FastWorker(Worker):
    threads: int

class Pipeline(MagicModel):
    workers: list[Worker]
    primary: Worker

pipeline = Pipeline.model_validate({
    "workers": [{"type": "fast", "name": "my_worker", "threads": 4}],
    "primary": "my_worker",
})
assert pipeline.primary is pipeline.workers[0]

Additionally, when validating fields of the type dict[str, NamedMagicModel], a validation helper NamedMagicModel.meta_from_key can be used to inject the instance name, and optionally type, from the dictionary key.

from typing import Annotated

from pydantic_magic import MagicModel, NamedMagicModel

class Worker(NamedMagicModel, abstract=True):
    pass

class FastWorker(Worker):
    threads: int

class Pipeline(MagicModel):
    # "type:name" key injects both type discriminator and instance name, update_key writes back
    # instance name to validated dictionary.
    workers: Annotated[dict[str, Worker], Worker.meta_from_key(update_key=True)]
    primary: Worker

pipeline = Pipeline.model_validate({
    "workers": {"fast:my_worker": {"threads": 4}},
    "primary": "my_worker",
})
assert isinstance(pipeline.primary, FastWorker)
assert {"my_worker": pipeline.primary} == pipeline.workers

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_magic-0.1.0.tar.gz (12.6 kB view details)

Uploaded Source

Built Distribution

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

pydantic_magic-0.1.0-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pydantic_magic-0.1.0.tar.gz
  • Upload date:
  • Size: 12.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for pydantic_magic-0.1.0.tar.gz
Algorithm Hash digest
SHA256 5d66d50d4c6891a9249288046491acbe612d565a3195b957d3d75312f4405237
MD5 6cce58a455294231dabad5b027faee7f
BLAKE2b-256 027e4e6e9686f65b080da132873aa0e9baaf9dd9be4d31e83a6df43fd8821ff5

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pydantic_magic-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for pydantic_magic-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bd9da5a4434b63288759480ed60608bbfcd96f93b054e076757317223abf4df6
MD5 0dc3ccb7b33992ed81cb8c73bcf840ce
BLAKE2b-256 f181f8adcf2095d686a757c1694508652abc8d2841c48bfdb59a2b2fc919733a

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