-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathnode.py
More file actions
49 lines (41 loc) · 1.55 KB
/
node.py
File metadata and controls
49 lines (41 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from typing import Any
class Node:
"""
Represents a node in a hierarchical document/tree structure.
Each node has a unique identifier (id) and a parent node (parent), both integers.
"""
__slots__ = ('id', 'parent') # Memory optimization and faster attribute access
id: int
parent: int
def __init__(self, id: int, parent: int) -> None:
"""
Initialize a Node instance with id and parent.
Raises:
ValueError: If id or parent are not integers, or if parent is invalid.
"""
if not isinstance(id, int) or not isinstance(parent, int):
raise ValueError("Both id and parent must be integers.")
if parent == id:
raise ValueError("A node cannot be its own parent.")
if parent > id:
raise ValueError("Parent id cannot be greater than node id.")
self.id = id
self.parent = parent
def __repr__(self) -> str:
"""
Return the string representation of the Node that allows recreation using eval().
Example: Node(2, 1)
"""
return f"Node({self.id}, {self.parent})"
def __eq__(self, other: Any) -> bool:
"""
Compare Node equality based on id and parent.
"""
if not isinstance(other, Node):
return NotImplemented
return self.id == other.id and self.parent == other.parent
def __hash__(self) -> int:
"""
Provide a hash function to allow using Node in sets or as dict keys.
"""
return hash((self.id, self.parent))