API reference¶
Everything exported from the pydynantic top-level package. Each symbol below is
generated directly from its docstring and signature.
pydynantic ¶
pydynantic: single-table design for DynamoDB, with typed Pydantic entities.
OperationHook
module-attribute
¶
OperationHook = Callable[[OperationEvent], None]
A callable invoked once per DynamoDB operation; receives an :class:OperationEvent.
Collection ¶
Base class for a set of entities sharing a partition.
Declare members = [User, Membership, Invoice] on the subclass; all
members must compose the same partition key. Query a partition with
OrgData.query(org_id="acme").all() and read results as result.users,
result.invoices (the entity name pluralised).
query
classmethod
¶
query(*, attributes=None, **pk_attrs)
Query a partition for all member entity types.
attributes limits the response to a projection of attribute paths;
omitted fields fall back to their model defaults (or fail validation if
required), so include everything each member needs to construct. The
discriminator attribute is always included so bucketing still works.
CollectionPage
dataclass
¶
A single page of a collection query plus a cursor for the next page.
result is a :class:CollectionResult bucketing the page's items by
entity type; cursor is an opaque next-page token (None when the
partition is drained).
CollectionResult ¶
Holds the items of a collection query, bucketed per entity type.
Entity ¶
Bases: BaseModel
Base class for single-table entities.
Subclass with class User(Entity, table=table, name="user"): ... and
declare key templates on an inner Meta class via :func:pydynantic.key.
from_dynamo
classmethod
¶
from_dynamo(item)
Deserialize a raw DynamoDB item into an entity instance.
build_key
classmethod
¶
build_key(attrs)
Build the primary-key portion of an item from attribute values.
put
classmethod
¶
put(item, *, condition=None, return_values='NONE')
Create or replace an item. Supports optimistic locking and conditions.
put always returns the written item (the object you passed in),
so put(x) is x. return_values="ALL_OLD" asks DynamoDB to surface
the pre-write stored state at the API level, but put's return value
is unchanged — and with optimistic locking the returned object carries
the bumped version. Only NONE and ALL_OLD are valid.
get
classmethod
¶
get(*, consistent=False, attributes=None, **key_attrs)
Fetch an item by its primary key, or None if it does not exist.
attributes limits the response to a projection of attribute paths;
omitted fields fall back to their model defaults (or fail validation if
required), so include everything the entity needs to construct.
get_or_raise
classmethod
¶
get_or_raise(*, consistent=False, attributes=None, **key_attrs)
Like :meth:get but raises :class:ItemNotFoundError when missing.
Accepts the same consistent and attributes read options as
:meth:get.
delete
classmethod
¶
delete(*, condition=None, return_values='NONE', **key_attrs)
Delete an item by its primary key.
With return_values="ALL_OLD" the deleted item is returned (or
None if it did not exist); otherwise delete returns None.
Only NONE and ALL_OLD are valid.
update
classmethod
¶
update(*, set=None, remove=None, add=None, delete=None, condition=None, expected_version=None, return_values='ALL_NEW', **key_attrs)
Apply a partial update via a generated UpdateExpression.
set assigns attributes, remove deletes them, add performs
atomic numeric/set additions, delete removes elements from sets.
Any GSI key whose source attributes change is recomputed automatically.
On a versioned entity, pass expected_version to guard the write with
the version you last read: a concurrent change raises
:class:~pydynantic.OptimisticLockError instead of silently overwriting
it. The stored version is always incremented regardless.
batch_get
classmethod
¶
batch_get(keys, *, consistent=False, attributes=None)
Fetch many items by key, chunking and retrying transparently.
attributes limits the response to a projection of attribute paths;
omitted fields fall back to their model defaults (or fail validation if
required), so include everything the entity needs to construct.
batch_write
classmethod
¶
batch_write(*, puts=None, deletes=None)
Write/delete many items, chunking and retrying unprocessed items.
scan
classmethod
¶
scan()
Return a builder for a full-table scan restricted to this entity.
A scan reads the whole table; the builder automatically filters on the
__entity__ discriminator so only this entity's items are returned.
Prefer :attr:query whenever a key condition applies.
ConditionCheckFailedError ¶
Bases: PydynanticError
Raised when a write fails because its condition expression was not met.
ItemNotFoundError ¶
Bases: PydynanticError
Raised when a required item does not exist (e.g. get/one).
KeyTemplateError ¶
Bases: PydynanticError
Raised when a key template references an attribute that is missing.
MultipleResultsError ¶
Bases: PydynanticError
Raised by one/one_or_none when more than one item matches.
OptimisticLockError ¶
Bases: ConditionCheckFailedError
Raised when a versioned write loses an optimistic-locking race.
PydynanticError ¶
Bases: Exception
Base class for every error raised by pydynantic.
TransactionCanceledError ¶
Bases: PydynanticError
Raised when a TransactWriteItems call is cancelled.
The per-action cancellation reasons (as returned by DynamoDB) are
exposed on the reasons attribute for diagnostics.
ValidationError ¶
Bases: PydynanticError
Wraps a :class:pydantic.ValidationError for schema violations.
Condition ¶
Base class for all expression nodes. Combine with &, |, ~.
F ¶
Reference to an attribute, used to build :class:Condition objects.
Supports dotted paths for nested map attributes, e.g. F("address.city").
KeyDefinition ¶
A primary or secondary-index key declared on an entity's Meta.
Instances are created by the :func:key factory and bound to a concrete
:class:~pydynantic.table.Table (which resolves the physical attribute
names) when the owning entity class is created.
referenced_fields
property
¶
referenced_fields
All entity attributes this key reads, across its pk and sk templates.
key_attributes ¶
key_attributes(attrs)
Return the physical key attributes (pk/sk) for an item.
Returns an empty mapping if the required attributes for this key are not all present, which lets non-projected entities skip optional GSIs.
OperationEvent
dataclass
¶
A single DynamoDB operation, reported to an :data:OperationHook.
Page
dataclass
¶
Bases: Generic[T]
A single page of query results plus a cursor for the next page.
QueryBuilder ¶
Bases: Generic[E]
Fluent builder for a query against one declared key (primary or GSI).
consistent ¶
consistent(value=True)
Request a strongly consistent read. Mirrors get(consistent=...).
GSIs only support eventually consistent reads, so requesting a consistent read against an index is rejected eagerly.
one_or_none ¶
one_or_none()
Return the single match, None if none, error if more than one.
Any user .limit() is ignored: this always probes for a second item
so the "multiple results" case is never silently masked.
one ¶
one()
Return the single match, raising if zero or more than one.
Any user .limit() is ignored: this always probes for a second item
so the "multiple results" case is never silently masked.
QueryNamespace ¶
Bases: Generic[E]
Entity.query accessor exposing one builder per declared key.
ScanBuilder ¶
Bases: Generic[E]
Fluent builder for a full-table scan restricted to one entity type.
filter ¶
filter(condition)
Add a filter expression applied after the scan; chained calls AND-combine.
Index
dataclass
¶
A secondary index's physical key attribute names.
Table ¶
Configuration for a single physical DynamoDB table.
The boto3 client is injected (defaulting to boto3.client("dynamodb"))
so credentials, region and endpoint stay the caller's concern and tests can
inject a mocked client.
Transaction ¶
Accumulates write actions and flushes them atomically on commit.
created_at_attr ¶
created_at_attr(**kwargs)
Mark a datetime | None field as the auto-managed creation timestamp.
On the first put (when the field is still None) pydynantic stamps the
field with datetime.now(timezone.utc). Subsequent puts leave it untouched,
and update never modifies it.
ttl_attr ¶
ttl_attr(default=None, **kwargs)
Mark a field as the DynamoDB Time-To-Live (TTL) attribute.
DynamoDB requires the TTL attribute to be a Number holding a Unix epoch
timestamp in seconds. The field may be declared as a datetime | None (the
common case) or an int; on every put the stored value is overridden to
an epoch-seconds Number regardless of the model's default ISO datetime
encoding. Reading back coerces the epoch into a datetime (UTC), so
sub-second precision is dropped.
The default is None (TTL is optional). When the value is None the
attribute is omitted from the stored item entirely.
Timezone: TTL datetime values should be timezone-aware. Naive datetimes
are passed to .timestamp() unchanged (interpreted in the local timezone by
Python); pydynantic does not reinterpret them, so prefer tz-aware values.
updated_at_attr ¶
updated_at_attr(**kwargs)
Mark a datetime | None field as the auto-managed modification timestamp.
On every put the field is stamped with datetime.now(timezone.utc). On
update it is stamped too, unless the caller explicitly supplies it in
set= (in which case the caller's value wins).
version_attr ¶
version_attr(default=0, **kwargs)
Mark an integer field as the optimistic-locking version attribute.
On every versioned put, the version is incremented and a condition is
added requiring the stored version to match; a lost race raises
:class:~pydynantic.errors.OptimisticLockError.
attr_not_exists ¶
attr_not_exists(path)
Convenience: attribute_not_exists(path) (e.g. create-only puts).
key ¶
key(*, pk, sk=None, index=None)
Declare a key template for an entity.
:param pk: partition-key template, e.g. "ORG#{org_id}".
:param sk: optional sort-key template, e.g. "USER#{user_id}".
:param index: GSI name (from the table's indexes); None = primary.
decode_cursor ¶
decode_cursor(cursor)
Decode an opaque cursor back into a DynamoDB ExclusiveStartKey.
None decodes to None. The cursor must be exactly the opaque,
versioned token produced by :func:encode_cursor -- it is never
hand-built. Any malformed, non-JSON, structurally-wrong or
unsupported-version cursor raises :class:~pydynantic.errors.PydynanticError
rather than leaking a raw decoding exception.
encode_cursor ¶
encode_cursor(last_evaluated_key)
Encode a DynamoDB LastEvaluatedKey into an opaque cursor string.
Returns a versioned, base64url-encoded token without = padding
(HTTP/JSON-safe). None or an empty key yields None. The result is
opaque: pass it back verbatim to resume pagination; do not parse or build
one by hand.
transaction ¶
transaction(table)
Context manager that commits queued actions on a clean exit.
If the with block raises, commit is never reached, so no actions are
sent (rollback). If a queued condition fails at commit time, DynamoDB
cancels the whole transaction atomically.
Re-exported from Pydantic¶
pydynantic re-exports Pydantic's Field
for convenience, so you can declare entity attribute metadata without a second import. It
behaves exactly like pydantic.Field; see the linked Pydantic docs for every parameter.
pydantic.Field ¶
Field(default: ellipsis, *, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, exclude_if: Callable[[Any], bool] | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: Deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: bool | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) -> Any
Field(default: Any, *, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, exclude_if: Callable[[Any], bool] | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: Deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: Literal[True], repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) -> Any
Field(default: _T, *, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, exclude_if: Callable[[Any], bool] | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: Deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: Literal[False] = ..., repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) -> _T
Field(*, default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any], alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, exclude_if: Callable[[Any], bool] | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: Deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: Literal[True], repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) -> Any
Field(*, default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T], alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, exclude_if: Callable[[Any], bool] | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: Deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: Literal[False] | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) -> _T
Field(*, alias: str | None = _Unset, alias_priority: int | None = _Unset, validation_alias: str | AliasPath | AliasChoices | None = _Unset, serialization_alias: str | None = _Unset, title: str | None = _Unset, field_title_generator: Callable[[str, FieldInfo], str] | None = _Unset, description: str | None = _Unset, examples: list[Any] | None = _Unset, exclude: bool | None = _Unset, exclude_if: Callable[[Any], bool] | None = _Unset, discriminator: str | Discriminator | None = _Unset, deprecated: Deprecated | str | bool | None = _Unset, json_schema_extra: JsonDict | Callable[[JsonDict], None] | None = _Unset, frozen: bool | None = _Unset, validate_default: bool | None = _Unset, repr: bool = _Unset, init: bool | None = _Unset, init_var: bool | None = _Unset, kw_only: bool | None = _Unset, pattern: str | Pattern[str] | None = _Unset, strict: bool | None = _Unset, coerce_numbers_to_str: bool | None = _Unset, gt: SupportsGt | None = _Unset, ge: SupportsGe | None = _Unset, lt: SupportsLt | None = _Unset, le: SupportsLe | None = _Unset, multiple_of: float | None = _Unset, allow_inf_nan: bool | None = _Unset, max_digits: int | None = _Unset, decimal_places: int | None = _Unset, min_length: int | None = _Unset, max_length: int | None = _Unset, union_mode: Literal['smart', 'left_to_right'] = _Unset, fail_fast: bool | None = _Unset, **extra: Unpack[_EmptyKwargs]) -> Any
Field(default=PydanticUndefined, *, default_factory=_Unset, alias=_Unset, alias_priority=_Unset, validation_alias=_Unset, serialization_alias=_Unset, title=_Unset, field_title_generator=_Unset, description=_Unset, examples=_Unset, exclude=_Unset, exclude_if=_Unset, discriminator=_Unset, deprecated=_Unset, json_schema_extra=_Unset, frozen=_Unset, validate_default=_Unset, repr=_Unset, init=_Unset, init_var=_Unset, kw_only=_Unset, pattern=_Unset, strict=_Unset, coerce_numbers_to_str=_Unset, gt=_Unset, ge=_Unset, lt=_Unset, le=_Unset, multiple_of=_Unset, allow_inf_nan=_Unset, max_digits=_Unset, decimal_places=_Unset, min_length=_Unset, max_length=_Unset, union_mode=_Unset, fail_fast=_Unset, **extra)