Skip to content

BaseEntity

Base class for entities, domain objects with unique identity that live within an aggregate. Entities are always accessed through their parent aggregate and cannot exist independently.

See Entities guide for practical usage and Entities concept for design rationale.

Bases: Element, BaseModel, OptionsMixin

Base class for entities, domain objects with a unique identity that live within an aggregate.

Entities are mutable. Two entities are equal when they have the same identifier, whatever their other attribute values. Assigning a field validates the new value and runs the entity's pre and post invariants.

Fields are declared with Python type annotations and optional Field constraints. An id identity field is added unless one is declared with identifier=True.

The state_ property reports whether the entity is new, persisted, changed or destroyed. Events an entity raises are recorded on its aggregate root. See the entities guide.

Meta Options

Option Type Description
part_of type The aggregate this entity belongs to, or the parent entity for a nested entity. Required.
database str The [databases.*] entry that persists it (default: "default").
schema_name str The storage table/collection name.
auto_add_id_field bool Whether to auto-inject an id field (default: True).
Source code in src/protean/core/entity.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def __init__(self, *args: Any, **kwargs: Any) -> None:
    # Pop internal kwargs that should not reach Pydantic
    owner = kwargs.pop("_owner", None)
    root = kwargs.pop("_root", None)
    # _version is a PrivateAttr; accept it in kwargs for backward
    # compatibility (e.g. repository hydration) but set it after init.
    _version_value = kwargs.pop("_version", None)

    # Pop association/VO descriptor kwargs and shadow field kwargs before
    # Pydantic init.  Shadow fields (e.g. order_id, billing_address_street)
    # are set dynamically during domain resolution and must not be passed
    # to Pydantic's __init__ which rejects them with extra="forbid".
    entity_cls = type(self)
    values = _split_init_values(
        args,
        kwargs,
        _shadow_field_names(entity_cls),
        lambda name: self._get_class_descriptor(entity_cls, name) is not None,
    )
    descriptor_kwargs = values.descriptor_kwargs
    shadow_kwargs = values.shadow_kwargs

    # Collect all validation errors (Pydantic + required descriptors) before raising
    collected_errors: dict[str, list[str]] = {}

    # Push init context onto the thread-local stack so that
    # model_post_init (called by Pydantic inside super().__init__())
    # can retrieve descriptor/shadow kwargs.  Pydantic wipes __dict__
    # during validation, so we cannot stash data on the instance.
    stack: list[dict[str, Any]] = getattr(_init_context, "stack", [])
    depth_before_init = len(stack)
    stack.append(
        {
            "descriptor_kwargs": descriptor_kwargs,
            "shadow_kwargs": shadow_kwargs,
            "owner": owner,
            "root": root,
            "_version": _version_value,
        }
    )
    _init_context.stack = stack

    try:
        super().__init__(**values.kwargs)
    except PydanticValidationError as e:
        collected_errors.update(convert_pydantic_errors(e))
    finally:
        # ``model_post_init`` pops this call's entry on a successful init.
        # When construction raises before it runs (Pydantic field validation
        # fails, or an abstract class is rejected), the entry is left behind,
        # and a caller that catches the error in a loop (the snapshot loader
        # reloading a stale aggregate) leaks one entry per attempt. Truncate
        # to the pre-push depth so this call's entry is balanced for any
        # construction exception, without popping a parent or double-popping
        # one ``model_post_init`` already removed.
        del stack[depth_before_init:]

    _add_missing_required_errors(
        entity_cls, descriptor_kwargs, shadow_kwargs, collected_errors
    )

    if collected_errors:
        raise ValidationError(collected_errors)

state_ property writable

state_: _EntityState

Access entity lifecycle state.

__track_id_field classmethod

__track_id_field() -> None

Find the field marked identifier=True and record its name.

Source code in src/protean/core/entity.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
@classmethod
def __track_id_field(cls) -> None:
    """Find the field marked ``identifier=True`` and record its name."""
    id_fields = [
        field
        for _, field in getattr(cls, _FIELDS, {}).items()
        if getattr(field, "identifier", False)
    ]

    if len(id_fields) > 1:
        raise NotSupportedError(
            {
                "_entity": [
                    (
                        f"Multiple identifier fields found in entity {cls.__name__}. "
                        "Only one identifier field is allowed."
                    )
                ]
            }
        )
    elif len(id_fields) == 1:
        setattr(cls, _ID_FIELD_NAME, id_fields[0].field_name)

defaults

defaults() -> None

Placeholder for defaults.

Override in subclass when an attribute's default depends on other attribute values.

Source code in src/protean/core/entity.py
646
647
648
649
650
def defaults(self) -> None:
    """Placeholder for defaults.

    Override in subclass when an attribute's default depends on other attribute values.
    """

can_transition_to

can_transition_to(
    field_name: str, target_value: Any
) -> bool

Check whether a status field can transition to the given value.

Returns True if the transition is valid, False otherwise. Always returns True for non-status fields or status fields without a transitions map.

Example::

if order.can_transition_to("status", OrderStatus.SHIPPED):
    order.ship(tracking_number="ABC123")
Source code in src/protean/core/entity.py
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
def can_transition_to(self, field_name: str, target_value: Any) -> bool:
    """Check whether a status field can transition to the given value.

    Returns ``True`` if the transition is valid, ``False`` otherwise.
    Always returns ``True`` for non-status fields or status fields
    without a transitions map.

    Example::

        if order.can_transition_to("status", OrderStatus.SHIPPED):
            order.ship(tracking_number="ABC123")
    """

    fields_dict = getattr(self.__class__, _FIELDS, {})
    field_obj = fields_dict.get(field_name)
    if field_obj is None or not isinstance(field_obj, ResolvedField):
        return True
    transitions = field_obj.transitions
    if not transitions:
        return True

    current_value = getattr(self, field_name, None)
    target = target_value.value if isinstance(target_value, Enum) else target_value
    current = (
        current_value.value if isinstance(current_value, Enum) else current_value
    )

    if current is None:
        return True

    if current not in transitions:
        return False

    return target in transitions[current]

raise_

raise_(event: Any) -> None

Raise an event in the aggregate cluster.

The event is always registered on the aggregate root, irrespective of where it is raised in the entity cluster.

Source code in src/protean/core/entity.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
def raise_(self, event: Any) -> None:
    """Raise an event in the aggregate cluster.

    The event is always registered on the aggregate root, irrespective
    of where it is raised in the entity cluster.
    """
    if event.meta_.part_of != self._root.__class__:
        raise ConfigurationError(
            f"Event `{event.__class__.__name__}` is not associated with"
            f" aggregate `{self._root.__class__.__name__}`"
        )

    # Delegate to the root aggregate's raise_ (BaseAggregate overrides this)
    self._root.raise_(event)

to_dict

to_dict() -> dict[str, Any]

Return entity data as a dictionary.

Reference fields are skipped (they are navigation, not data). ValueObject fields are included only when non-None.

Source code in src/protean/core/entity.py
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
def to_dict(self) -> dict[str, Any]:
    """Return entity data as a dictionary.

    Reference fields are skipped (they are navigation, not data).
    ValueObject fields are included only when non-None.
    """
    result: dict[str, Any] = {}
    for fname, field_obj in getattr(self, _FIELDS, {}).items():
        if isinstance(field_obj, Reference):
            continue

        value = getattr(self, fname, None)

        if isinstance(field_obj, ValueObject):
            # Present, not truthy: ``as_dict`` returns ``None`` only
            # when the VO is ``None``, so an all-default VO is still included.
            dict_value = field_obj.as_dict(value)
            if dict_value is not None:
                result[fname] = dict_value
        elif isinstance(field_obj, Association):
            # HasOne/HasMany: delegate to descriptor's as_dict
            result[fname] = field_obj.as_dict(value)
        else:
            result[fname] = field_obj.as_dict(value)
    return result

from_value_object classmethod

from_value_object(vo: BaseValueObject) -> Self

Construct an entity instance from a value object.

This is the inverse of value_object_from_entity() -- it converts a VO payload (typically carried in a command or event) back into an entity instance::

items = [OrderItem.from_value_object(item) for item in command.items]

None values on identifier/unique fields are stripped so that auto-generated identity fields receive their default rather than failing validation. Explicit None on other fields is preserved.

Source code in src/protean/core/entity.py
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
@classmethod
def from_value_object(cls, vo: "BaseValueObject") -> Self:
    """Construct an entity instance from a value object.

    This is the inverse of ``value_object_from_entity()`` -- it converts
    a VO payload (typically carried in a command or event) back into an
    entity instance::

        items = [OrderItem.from_value_object(item) for item in command.items]

    ``None`` values on identifier/unique fields are stripped so that
    auto-generated identity fields receive their default rather than
    failing validation.  Explicit ``None`` on other fields is preserved.
    """
    data = vo.to_dict()

    # Strip None only for identifier/unique fields so auto-generated
    # identity defaults kick in, while preserving intentional Nones.
    id_or_unique = set()
    for fname, field_obj in getattr(cls, _FIELDS, {}).items():
        if isinstance(field_obj, ResolvedField) and (
            field_obj.identifier or field_obj.unique
        ):
            id_or_unique.add(fname)

    return cls(
        **{k: v for k, v in data.items() if not (v is None and k in id_or_unique)}
    )

__deepcopy__

__deepcopy__(
    memo: dict[int, Any] | None = None,
) -> BaseEntity

Deep copy that handles circular _root/_owner references.

Pydantic's default deepcopy recurses infinitely when pydantic_private contains back-references to the entity itself (e.g. _root and _owner on aggregate roots).

Source code in src/protean/core/entity.py
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> "BaseEntity":
    """Deep copy that handles circular _root/_owner references.

    Pydantic's default __deepcopy__ recurses infinitely when
    __pydantic_private__ contains back-references to the entity
    itself (e.g. _root and _owner on aggregate roots).
    """
    if memo is None:
        memo = {}

    # Short-circuit if we've already been copied (prevents infinite loop)
    existing: BaseEntity | None = memo.get(id(self))
    if existing is not None:
        return existing

    cls = type(self)
    new_obj = cls.__new__(cls)
    memo[id(self)] = new_obj

    # Deep-copy __dict__ (Pydantic model fields and extras)
    object.__setattr__(new_obj, "__dict__", copy.deepcopy(self.__dict__, memo))
    object.__setattr__(
        new_obj,
        "__pydantic_extra__",
        copy.deepcopy(self.__pydantic_extra__, memo),
    )
    object.__setattr__(
        new_obj,
        "__pydantic_fields_set__",
        copy.copy(self.__pydantic_fields_set__),
    )

    # Deep-copy __pydantic_private__, with memo to break cycles
    private = getattr(self, "__pydantic_private__", None)
    if private is None:
        object.__setattr__(new_obj, "__pydantic_private__", None)
    else:
        object.__setattr__(
            new_obj,
            "__pydantic_private__",
            copy.deepcopy(private, memo),
        )

    return new_obj