Coverage for packages/kwai-core/src/kwai_core/domain/entity.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2024-01-01 00:00 +0000

1"""Module that defines a generic entity.""" 

2 

3from dataclasses import dataclass, field, fields, replace 

4from typing import ( 

5 Any, 

6 ClassVar, 

7 Self, 

8 Type, 

9) 

10 

11from kwai_core.domain.value_objects.identifier import IntIdentifier 

12from kwai_core.domain.value_objects.traceable_time import TraceableTime 

13 

14 

15@dataclass(frozen=True, slots=True, eq=False) 

16class DataclassEntity: 

17 """A base class for an entity. 

18 

19 An entity is immutable, so it cannot be modified. A method of an entity that 

20 changes the entity must allways return a new entity instance with the changed 

21 data. The method replace of dataclasses can be used for this. 

22 

23 Currently, this is a separate class to make it possible to migrate to this 

24 new class. In the future, the Entity class will be removed and this class 

25 will be renamed to Entity. 

26 

27 By default, id is of type IntIdentifier. Overwrite ID in an entity class if 

28 another identifier should be used. 

29 

30 Attributes: 

31 id: The id of the entity. 

32 traceable_time: Keeps track of the creation and update timestamp of the entity. 

33 """ 

34 

35 ID: ClassVar[Type] = IntIdentifier 

36 

37 id: ID = field(default_factory=ID) 

38 traceable_time: TraceableTime = field(default_factory=TraceableTime) 

39 version = 0 

40 

41 def set_id(self, id_: ID) -> Self: 

42 """Set the id for this entity. 

43 

44 This will raise a ValueError if the id was already set. 

45 If you need an entity with the same data but with another id, you should create 

46 a new entity with dataclasses.replace and replace the id. 

47 """ 

48 if not self.id.is_empty(): 

49 raise ValueError(f"{self.__class__.__name__} has already an ID: {self.id}") 

50 return replace(self, id=id_) 

51 

52 def shallow_dict(self) -> dict[str, Any]: 

53 """Return a dictionary representation of the entity. 

54 

55 !!! Note 

56 This method is not recursive. Use asdict from dataclasses when also 

57 nested fields must be returned as a dict. 

58 """ 

59 return {f.name: getattr(self, f.name) for f in fields(self)} 

60 

61 def __eq__(self, other: Any) -> bool: 

62 """Check if two entities are equal. 

63 

64 An entity equals another entity when the id is the same. 

65 """ 

66 return isinstance(other, type(self)) and other.id == self.id 

67 

68 def __hash__(self) -> int: 

69 """Generate a hash for this entity.""" 

70 return hash(self.id)