- Add AI code generation requirements to AGENTS.md - Add module-level docstrings to all 46 Python modules - Add detailed Google-style docstrings to all classes and functions - Remove all inline comments following self-documenting code principle - Include Args, Returns, Raises sections in function docstrings - Add Attributes and Examples sections to class docstrings
76 lines
2.2 KiB
Python
76 lines
2.2 KiB
Python
"""Base entity for DDD domain layer.
|
|
|
|
This module provides the foundational BaseEntity class that all domain
|
|
entities must inherit from. It implements common entity patterns including
|
|
identity management, equality comparison, and timestamp tracking.
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
from dataclasses import dataclass, field
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
from uuid import UUID, uuid4
|
|
|
|
|
|
@dataclass(kw_only=True)
|
|
class BaseEntity(ABC):
|
|
"""Base class for all domain entities.
|
|
|
|
Provides common functionality for domain entities including unique
|
|
identification, creation/update timestamps, and equality comparison
|
|
based on identity.
|
|
|
|
Attributes:
|
|
id: Unique identifier for the entity, automatically generated.
|
|
created_at: Timestamp when the entity was created.
|
|
updated_at: Timestamp when the entity was last updated.
|
|
|
|
Example:
|
|
>>> class User(BaseEntity):
|
|
... name: str
|
|
... def to_dict(self) -> dict[str, Any]:
|
|
... return {"id": str(self.id), "name": self.name}
|
|
"""
|
|
|
|
id: UUID = field(default_factory=uuid4)
|
|
created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
|
|
updated_at: datetime = field(default_factory=lambda: datetime.now(UTC))
|
|
|
|
def __eq__(self, other: object) -> bool:
|
|
"""Compare entities by identity.
|
|
|
|
Args:
|
|
other: Another object to compare with.
|
|
|
|
Returns:
|
|
True if both objects are BaseEntity instances with same ID.
|
|
"""
|
|
if not isinstance(other, BaseEntity):
|
|
return NotImplemented
|
|
return self.id == other.id
|
|
|
|
def __hash__(self) -> int:
|
|
"""Get hash based on entity identity.
|
|
|
|
Returns:
|
|
Hash of the entity ID.
|
|
"""
|
|
return hash(self.id)
|
|
|
|
def touch(self) -> None:
|
|
"""Update the updated_at timestamp.
|
|
|
|
Should be called whenever the entity is modified to track
|
|
the last modification time.
|
|
"""
|
|
self.updated_at = datetime.now(UTC)
|
|
|
|
@abstractmethod
|
|
def to_dict(self) -> dict[str, Any]:
|
|
"""Convert entity to dictionary representation.
|
|
|
|
Returns:
|
|
Dictionary containing all entity attributes.
|
|
"""
|
|
...
|