Skip to main content

Pydantic Super Model

Generic type introspection and Annotated field lookup for any Python class, with optional Pydantic integration.

Coverage

Features

  • Look up fields by their full Annotated alias or by a metadata type, matching metadata instances with isinstance.
  • Resolve metadata from the class, with no instance, wherever it lives: hoisted onto the field, nested inside a union member, or inside a nested Annotated.
  • See through named type aliases, including generic ones: type statements on Python 3.12+ and typing_extensions.TypeAliasType.
  • Read the concrete generic type parameter an instance was built with.
  • Reject fields marked as intentionally not implemented, checked automatically on Pydantic models.
  • Works with any Python class; the Pydantic mixin adds that validation and unset-None filtering.
  • Typed throughout, with a PEP 561 py.typed marker.

Installation

pip install pydantic-super-model

Mixins

Mixin Base Adds
SuperModelMixin any Python class annotation introspection and generic type resolution
SuperModelPydanticMixin Pydantic BaseModel automatic FieldNotImplemented validation, omits unset default None values

The examples below use SuperModelPydanticMixin. Each one works the same through SuperModelMixin, which reads values straight off the instance.

Quick Start

Annotate a field with any metadata object, then ask an instance for it:

from typing import Annotated

from pydantic_super_model import SuperModelPydanticMixin


class PrimaryKeyAnnotation:
    pass


PrimaryKey = Annotated[int, PrimaryKeyAnnotation]


class User(SuperModelPydanticMixin):
    id: PrimaryKey
    name: str


field_info = User(id=1, name="John Doe").get_annotated_fields(PrimaryKey)["id"]

field_info.value        # 1
field_info.annotation   # PrimaryKey
field_info.metadata     # (PrimaryKeyAnnotation,)

A plain class carries the same API once it inherits SuperModelMixin:

from pydantic_super_model import SuperModelMixin


class Account(SuperModelMixin):
    id: PrimaryKey

    def __init__(self, id: PrimaryKey) -> None:
        self.id = id


Account(id=1).get_annotated_fields(PrimaryKey)["id"].value   # 1

Annotated Field Lookup

get_annotated_fields returns the matching fields as a mapping of names to AnnotatedFieldInfo. A query matches either the full Annotated[...] alias or a metadata type, and falsy values such as 0 are included:

user = User(id=0, name="Zero")

user.get_annotated_fields(PrimaryKey)["id"].value             # 0
user.get_annotated_fields(PrimaryKeyAnnotation)["id"].value   # 0, matched by metadata type

get_annotated_field_value returns the first match instead of a mapping. It raises ValueError when nothing matches, unless allow_undefined=True, and when the matched value is None, unless allow_none=True:

user.get_annotated_field_value(PrimaryKey).value   # 0

Querying by class matches metadata instances, and matched_metadata carries the ones that matched:

class ThemeColorOptions:
    def __init__(self, *, palette: str) -> None:
        self.palette = palette


class Theme(SuperModelPydanticMixin):
    accent_color: Annotated[str, "theme_color", ThemeColorOptions(palette="northern-lights")]


field_info = Theme(accent_color="#7dd3fc").get_annotated_fields(ThemeColorOptions)["accent_color"]

field_info.metadata[0]                    # "theme_color"
field_info.matched_metadata[0].palette    # "northern-lights"

A Pydantic private attribute is not a field, so it is never reported here. get_annotated_declarations answers the wider question — every annotated declaration, private attributes included — and is what validate_not_implemented_fields checks:

from pydantic import PrivateAttr


class Draft(SuperModelPydanticMixin):
    id: PrimaryKey
    _scratch: PrimaryKey = PrivateAttr(default=2)


draft = Draft(id=1)

sorted(draft.get_annotated_fields(PrimaryKey))         # ["id"]
sorted(draft.get_annotated_declarations(PrimaryKey))   # ["_scratch", "id"]

On SuperModelPydanticMixin a field left at its default None is omitted, while a None passed explicitly is kept. SuperModelMixin keeps every None:

class OptionalUser(SuperModelPydanticMixin):
    id: PrimaryKey | None = None


OptionalUser().get_annotated_fields(PrimaryKey)          # {}, unset default
OptionalUser(id=None).get_annotated_fields(PrimaryKey)   # {"id": ...}, explicit None

Class-Level Metadata

Three classmethods answer "which fields of this class carry metadata X" with no instance in hand. Metadata is found both where Pydantic hoists it onto the field, for a bare Annotated[...], and where it stays nested inside a union member or a nested Annotated:

class ColumnOptions:
    def __init__(self, *, name: str) -> None:
        self.name = name


class Record(SuperModelPydanticMixin):
    identifier: Annotated[str, ColumnOptions(name="identifier")]
    label: Annotated[str, ColumnOptions(name="label")] | None = None
    plain: str = ""


Record.field_metadata("identifier", ColumnOptions)[0].name   # "identifier"
Record.field_metadata("plain", ColumnOptions)                # ()
Record.first_field_metadata("label", ColumnOptions).name     # "label"
Record.first_field_metadata("plain", ColumnOptions)          # None
Record.field_names_with_metadata(ColumnOptions)              # frozenset({"identifier", "label"})

field_metadata takes any number of metadata types and returns every instance of them, outermost annotation first, including from every member of a union. A field the class does not declare raises KeyError, whether or not any metadata types are requested.

Named type aliases are followed too. A generic alias keeps the metadata of the argument it is given, ahead of the alias's own metadata, as Python orders nested Annotated. Metadata written around a named alias comes before the metadata inside it:

class SearchOptions:
    def __init__(self, *, weight: int) -> None:
        self.weight = weight


type Column[T] = Annotated[T, SearchOptions(weight=1)]


class Table(SuperModelPydanticMixin):
    title: Column[Annotated[str, ColumnOptions(name="title")]] = ""


Table.field_metadata("title", SearchOptions, ColumnOptions)   # (ColumnOptions(...), SearchOptions(...))

collect_annotated_fields accepts a class as well as an instance. Given a class it resolves the type hints, so every value is None:

from pydantic_super_model import collect_annotated_fields

collect_annotated_fields(Record, ColumnOptions)["identifier"].value   # None

Generic Type Resolution

get_type returns the concrete generic parameter the instance was built with, or None:

from typing import Generic, TypeVar

from pydantic_super_model import SuperModelMixin

GenericType = TypeVar("GenericType")


class Box(SuperModelMixin, Generic[GenericType]):
    def __init__(self, value: GenericType) -> None:
        self.value = value


Box[int](value=1).get_type()   # <class 'int'>
Box(value=1).get_type()        # None, no parameter supplied

Not-Implemented Fields

FieldNotImplemented marks a field that should be removed rather than used. SuperModelPydanticMixin checks for it on construction:

from pydantic_super_model import FieldNotImplemented, SuperModelPydanticMixin


class Experimental(SuperModelPydanticMixin):
    test_field: Annotated[int, FieldNotImplemented]


Experimental(test_field=1)   # raises NotImplementedError

On a plain class, call validate_not_implemented_fields() yourself, usually at the end of __init__.

AnnotatedFieldInfo

The NamedTuple returned by get_annotated_fields and get_annotated_field_value:

Field Type Description
value Any The field's current value
annotation object The full type annotation
metadata tuple[object, ...] All metadata from Annotated
matched_metadata tuple[object, ...] Only the metadata that matched the query

Local Development

poetry install --all-extras              # install
poetry run pytest                        # run the tests
poetry run black .                       # format
poetry run isort .                       # sort imports
poetry run pylint pydantic_super_model   # lint
poetry run pyright                       # type check

Metadata

Release files for pydantic-super-model 2.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydantic-super-model 2.2.1
File Size Uploaded Provenance Actions
pydantic_super_model-2.2.1.tar.gz 12.2 kB With provenance Details for pydantic_super_model-2.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-super-model 2.2.1
File Interpreter ABI Platform Actions
pydantic_super_model-2.2.1-py3-none-any.whl Python 3 none any Details for pydantic_super_model-2.2.1-py3-none-any.whl

Total release size: 24.9 kB

Release files / pydantic_super_model-2.2.1.tar.gz

Download URL pydantic_super_model-2.2.1.tar.gz
Size 12.2 kB
Tags Source
SHA-256 checksum
How to use checksums
6f54eaa835746426422c2ffbfb7ecdc4063cb1a90a4da76c81c4515cdf94d62c
BLAKE2b-256 checksum
How to use checksums
622dbd0de162e7abc06537c2dc38bb22a0cfa7edad7bdd739da4c0d50d578aea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / pydantic_super_model-2.2.1-py3-none-any.whl

Download URL pydantic_super_model-2.2.1-py3-none-any.whl
Size 12.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
516487d006636147f9ac74cb8d42b3215aec1ea1149bd1a825d183de99b6cc4b
BLAKE2b-256 checksum
How to use checksums
6a7d751e07f5c0d3c80e80657778910640f763230fdbb2872cdf4fb9155503d6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for pydantic-super-model 2.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pydantic_super_model-2.2.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page