Skip to content

Commit eebced4

Browse files
Implement a hash method for Component
Objects of the `Component` type are used in `ComponentGraph` in sets. The implicit hash method works there for now, but adding new members to the `Component` class may make it unhashable in the future, if the added members themselves are unhashable. Implementing an explicit hash method here removes this burden from from future member types. Component IDs are supposed to be unique in a microgrid, therefore hashing a `Component` object just based on its component ID is enough. Signed-off-by: Tiyash Basu <[email protected]>
1 parent 3551cd3 commit eebced4

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

src/frequenz/sdk/microgrid/component/_component.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,14 @@ def is_valid(self) -> bool:
125125
self.component_id > 0 and any(t == self.category for t in ComponentCategory)
126126
) or (self.component_id == 0 and self.category == ComponentCategory.GRID)
127127

128+
def __hash__(self) -> int:
129+
"""Compute a hash of this instance, obtained by hashing the `component_id` field.
130+
131+
Returns:
132+
Hash of this instance.
133+
"""
134+
return hash(self.component_id)
135+
128136

129137
class ComponentMetricId(Enum):
130138
"""An enum representing the various metrics available in the microgrid."""

0 commit comments

Comments
 (0)