Observed since 20 Oct, 17:33 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
Python Pydantic support of TypeScript-style utility types, including Partial, Required, Pick, and Omit. Useful for PATCH endpoints driven from BaseModel / SQLModel classes.
Python Pydantic support of TypeScript-style utility types, including Partial, Required, Pick, and Omit. Useful for PATCH endpoints driven from BaseModel / SQLModel classes.
🦜🕸️
Python is missing a key feature of modern day dynamic programming languages.
Namely, TypeScript supports these utility types: https://www.typescriptlang.org/docs/handbook/utility-types.html
Because of this missing support in python, developers are often encouraged to duplicate their models & field definitions between their API and ORM definitions, which becomes a really tedious and feels like it involves double handling.
Especially for PATCH endpoints when we want to update something, should we really need to manually redefine the schema? Especially with larger nested JSON schemas, and even with Discriminated Unions, it becomes a really cumbersome and limited chore a developer must do to separate the API schema from their application models, when there is almost always an overlap in structure and field definitions.
This is the motivation behind building "PATCH for Pydantic".
Ultimately, with the really mature pydantic library, it actually makes building a package like this not too complicated.
Since this is just a package, and not a service, there is no real "run" action. But you can run the tests immediately.
Here are a list of available commands via make.
make install - install the required dependencies.make test - runs the tests.make build-docker - build the docker image.make run-docker - run the docker compose services.make test-docker - run the tests in docker.make clean-docker - remove all docker containers etc.Install uv, (if you haven't already)
https://docs.astral.sh/uv/getting-started/installation/#installation-methods
brew install uv
Initialise pre-commit (validates ruff on commit.)
uv run pre-commit install
Install dependencies (including dev dependencies)
uv sync
If you are adding a new dev dependency, please run:
uv add --dev {your-new-package}
Packages all share the same namespace ab_core. To import this package into
your project:
from ab_core.template import placeholder_func
We encourage you to make your package available to all of ab via this
ab_core namespace. The goal is to streamline development, POCs and overall
collaboration.
The library is available on PyPI. You can install it using the following command:
Using pip:
pip install ab-pydantic-patch
Using UV
Note: there is currently no nice way like poetry, hence we still needd to provide the full url. https://github.com/astral-sh/uv/issues/10140
Add the dependency
uv add ab-pydantic-patch
Using poetry:
Then run the following command to install the package:
poetry add ab-pydantic-patch
Select a subset of fields.
Before
class User(BaseModel):
id: int
name: str
email: str
Transform
UserPick = Pick[User](fields={"id", "name"})
After (conceptual)
class UserPick(BaseModel):
id: int
name: str
type User = {
id: number
name: string
email: string
}
type UserPick = Pick<User, "id" | "name">
Remove specific fields.
Before
class User(BaseModel):
id: int
name: str
email: str
Transform
UserOmit = Omit[User](fields={"email"})
After (conceptual)
class UserOmit(BaseModel):
id: int
name: str
type User = {
id: number
name: string
email: string
}
type UserOmit = Omit<User, "email">
Make fields optional.
Before
class User(BaseModel):
id: int
name: str
Transform
UserPartial = Partial[User](fields={"name"})
After (conceptual)
class UserPartial(BaseModel):
id: int
name: str | None = None
type User = {
id: number
name: string
}
type UserPartial = Partial<Pick<User, "name">> & Pick<User, "id">
Force fields to be required.
Before
class User(BaseModel):
id: int | None = None
name: str | None = None
Transform
UserRequired = Required[User](fields={"id"})
After (conceptual)
class UserRequired(BaseModel):
id: int
name: str | None = None
type User = {
id?: number
name?: string
}
type UserRequired = Required<Pick<User, "id">> & Omit<User, "id">
Before
class User(BaseModel):
id: int
name: str
email: str
Transform
UserPatch = Patch[User](
pick={"id", "name"},
partial={"name"},
required={"id"},
)
After (conceptual)
class UserPatch(BaseModel):
id: int
name: str | None = None
set() vs NonePatch[User](partial=None)
→ all fields optional
class UserPatch(BaseModel):
id: int | None = None
name: str | None = None
email: str | None = None
Patch[User](partial=set())
→ no fields optional
class UserPatch(BaseModel):
id: int
name: str
email: str
Before
class Pet(BaseModel):
id: int
name: str
type: str
class Household(BaseModel):
id: int
owner_name: str
pets: list[Pet]
Transform
HouseholdPatch = Patch[Household](
pick={"id", "pets"},
required={"id"},
child_models={
Pet: PatchConfig(
pick={"id", "name"},
partial={"name"},
)
}
)
After (conceptual)
class PetPatch(BaseModel):
id: int
name: str | None = None
class HouseholdPatch(BaseModel):
id: int
pets: list[PetPatch] | None = None
Before
from typing import Annotated, Union, Literal
from pydantic import Field
class Cat(BaseModel):
kind: Literal["cat"]
id: int
name: str
class Dog(BaseModel):
kind: Literal["dog"]
id: int
name: str
Pet = Annotated[Union[Cat, Dog], Field(discriminator="kind")]
class Owner(BaseModel):
pet: Pet
Transform
OwnerPatch = Patch[Owner](
pick={"pet"},
child_models={
Cat: PatchConfig(
pick={"kind", "id", "name"},
partial={"name"},
),
Dog: PatchConfig(
pick={"kind", "id", "name"},
partial={"name"},
),
}
)
After (conceptual)
class CatPatch(BaseModel):
kind: Literal["cat"]
id: int
name: str | None = None
class DogPatch(BaseModel):
kind: Literal["dog"]
id: int
name: str | None = None
PetPatch = Annotated[
CatPatch | DogPatch,
Field(discriminator="kind")
]
class OwnerPatch(BaseModel):
pet: PetPatch | None = None
Before
from sqlmodel import SQLModel, Field, Relationship
class Pet(SQLModel, table=True):
id: int = Field(primary_key=True)
name: str
household_id: int | None = Field(default=None, foreign_key="household.id")
class Household(SQLModel, table=True):
id: int = Field(primary_key=True)
pets: list[Pet] = Relationship(back_populates="household")
Transform
HouseholdPatch = Patch[Household](
pick={"id", "pets"},
required={"id"},
child_models={
Pet: PatchConfig(
pick={"id", "name"},
)
}
)
After (conceptual)
class PetPatch(BaseModel):
id: int
name: str | None = None
class HouseholdPatch(BaseModel):
id: int
pets: list[PetPatch] | None = None
pydantic-patch supports Pydantic @computed_field values in generated models.
Computed fields are treated like regular fields for transformation purposes, so they can be selected, omitted, made optional, or made required using Pick, Omit, Partial, Required, and Patch.
Before
from pydantic import BaseModel, computed_field
class User(BaseModel):
first_name: str
last_name: str
@computed_field
@property
def full_name(self) -> str:
return f"{self.first_name} {self.last_name}"
Transform
UserDisplay = Pick[User](fields={"full_name"})
UserPatch = Patch[User](
pick={"first_name", "full_name"},
partial={"first_name"},
required={"full_name"},
)
After (conceptual)
class UserDisplay(BaseModel):
full_name: str
class UserPatch(BaseModel):
first_name: str | None = None
full_name: str
Computed fields become part of the generated model payload, which means they:
pick / omitpartialrequiredWhen using recursive_patch_orm_scalar(...), computed fields from patch payloads are ignored unless they correspond to real mapped ORM scalar attributes or relationships.
pydantic-patch supports SQLAlchemy @hybrid_property descriptors on SQLModel
classes.
Hybrid properties are treated like regular generated model fields, so they can
be selected, omitted, made optional, or made required using Pick, Omit,
Partial, Required, and Patch. Their return annotations are used as the
generated Pydantic field type.
Before
from sqlalchemy.ext.hybrid import hybrid_property
from sqlmodel import Field, SQLModel
class User(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
first_name: str
last_name: str
age: int
@hybrid_property
def full_name(self) -> str:
return f"{self.first_name} {self.last_name}"
@full_name.expression
def full_name(cls):
return cls.first_name + " " + cls.last_name
@hybrid_property
def is_adult(self) -> bool:
return self.age >= 18
@is_adult.expression
def is_adult(cls):
return cls.age >= 18
Transform
UserPatch = Patch[User](
pick={"first_name", "last_name", "age", "full_name", "is_adult"},
partial={"first_name", "last_name", "age"},
required={"full_name", "is_adult"},
)
After (conceptual)
class UserPatch(BaseModel):
first_name: str | None = None
last_name: str | None = None
age: int | None = None
full_name: str
is_adult: bool
Hybrid properties become part of the generated model payload, which means they:
pick / omitpartialrequiredfrom_attributesRequired hybrid properties can also be derived from dict input when the source SQLModel can be validated from that same payload.
For a runnable FastAPI example, see:
uv run python src/ab_core/pydantic_patch/examples/sqlmodel_examples/sqlmodel_hybrid_properties.py
Applied in this order:
BaseModellist[...]dict[...]Union / Annotatedpydantic-patch automatically resolves forward references among already
imported sibling model classes.
Because the library is type-driven, it needs real Python types when generating
Pick, Omit, Partial, Required, or Patch models. This commonly affects
SQLModel relationships split across multiple files, where relationships are
declared using strings to avoid circular imports.
For example:
class Project(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
milestones: list["ProjectMilestone"] = Relationship(back_populates="project")
Calling Patch[Project](...) works when the referenced sibling models have
already been imported somewhere in the same package/module tree.
The recommended pattern is to expose related models from your models package:
# my_app/models/__init__.py
from my_app.models.project import Project
from my_app.models.project_milestone import ProjectMilestone
from my_app.models.project_task import ProjectTask
from my_app.models.task_comment import TaskComment
__all__ = [
"Project",
"ProjectMilestone",
"ProjectTask",
"TaskComment",
]
Then import from that package before creating patch schemas:
from my_app.models import Project, ProjectMilestone, ProjectTask, TaskComment
from ab_core.pydantic_patch.patch import Patch, PatchConfig
ProjectPatch = Patch[Project](
pick={"id", "name", "milestones"},
required={"id"},
child_models={
ProjectMilestone: PatchConfig(
pick={"id", "name", "tasks"},
),
ProjectTask: PatchConfig(
pick={"id", "title", "comments"},
),
TaskComment: PatchConfig(
pick={"id", "body"},
),
},
)
If the referenced model has not been imported, or the annotation points to a
genuinely missing type, pydantic-patch raises
ForwardReferencesNotSupported.
For SQLModel relationship annotations, prefer SQLAlchemy-compatible relationship strings such as:
parent: "Project" = Relationship(back_populates="milestones")
rather than:
parent: "Project | None" = Relationship(back_populates="milestones")
SQLAlchemy can resolve "Project" as a mapped class name, but it cannot resolve
"Project | None" as a relationship target.
recursive_patch_orm_scalarWhen using generated Patch[...] models with SQLModel / SQLAlchemy, you can
apply nested updates directly onto an existing ORM object graph using
recursive_patch_orm_scalar(...).
This recursively mutates the existing ORM instances in-place so SQLAlchemy can track and persist relationship changes naturally.
ProjectPatch = Patch[Project](
pick={"name", "milestones"},
child_models={
ProjectMilestone: PatchConfig(
pick={"id", "name", "tasks"},
),
ProjectTask: PatchConfig(
pick={"id", "title", "comments"},
),
TaskComment: PatchConfig(
pick={"id", "body"},
),
},
)
project = db_session.get(Project, project_id)
recursive_patch_orm_scalar(project, patch)
db_session.add(project)
db_session.commit()
This is especially useful for FastAPI PATCH endpoints backed by SQLModel relationships.
pydantic-patch supports recursive parent/child tree layouts where a model
contains a list of children of the same model type.
This is useful for quote line items, category trees, bill-of-materials trees, nested tasks, comments, folders, and other hierarchical data.
from sqlmodel import Field, Relationship, SQLModel
from ab_core.pydantic_patch.orm_patch import recursive_patch_orm_scalar
from ab_core.pydantic_patch.patch import Patch, PatchConfig
class QuoteLineItem(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
parent_id: int | None = Field(default=None, foreign_key="quote_line_item.id")
line_item_name: str = ""
quoted_base_cost: float = 0.0
parent: "QuoteLineItem" = Relationship(
back_populates="children",
sa_relationship_kwargs={
"remote_side": "QuoteLineItem.id",
},
)
children: list["QuoteLineItem"] = Relationship(back_populates="parent")
For SQLModel relationships, keep the relationship target annotation as
"QuoteLineItem" rather than "QuoteLineItem | None" so SQLAlchemy can resolve
the mapped class name.
QuoteLineItemPatch = Patch[QuoteLineItem](
name="QuoteLineItemPatch",
pick={
"id",
"line_item_name",
"quoted_base_cost",
"children",
},
partial={
"id",
"line_item_name",
"quoted_base_cost",
"children",
},
child_models={
QuoteLineItem: PatchConfig(
pick={
"id",
"line_item_name",
"quoted_base_cost",
"children",
},
partial={
"id",
"line_item_name",
"quoted_base_cost",
"children",
},
),
},
)
line_item = db_session.get(QuoteLineItem, line_item_id)
patch = QuoteLineItemPatch.model_validate(
{
"id": line_item_id,
"line_item_name": "Colorbond fence",
"children": [
{
"id": 10,
"line_item_name": "Colorbond panels",
"quoted_base_cost": 725.0,
},
{
"line_item_name": "New gate allowance",
"quoted_base_cost": 300.0,
},
],
}
)
recursive_patch_orm_scalar(line_item, patch)
db_session.add(line_item)
db_session.commit()
In this layout:
id are patched onto matching existing ORM childrenid are treated as new childrenchildren can recursively patch deeper descendantsFor a runnable example, see:
uv run python src/ab_core/pydantic_patch/examples/sqlmodel_examples/self_referencing_tree.py
We use Ruff as the formatter and linter. The pre-commit has hooks which runs checking and applies linting automatically. The CI validates the linting, ensuring main is always looking clean.
You can manually use these commands too:
make lint - check for linting issues.make format - fix linting issues.We publish to PyPI using Github releases. Steps are as follows:
pyproject.toml file using a PR and merge to
main. Use uv version --bump {patch/minor/major} to update the version.publish workflow. In the Release window, type in the
version number and it will prompt to create a new tag.Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 1.5.0 | 2 Jul 2026 | 3 |
This describes our collected data; it is not a security assessment.
Observed since 20 Oct, 17:33 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:3b6cb2af4588f58e7872e518c570133a2877f422829e63263989108bf1076372