| 1 |
from ..helpers import quote_string |
| 2 |
|
| 3 |
|
| 4 |
class Node: |
| 5 |
""" |
| 6 |
A node within the graph. |
| 7 |
""" |
| 8 |
|
| 9 |
def __init__(self, node_id=None, alias=None, label=None, properties=None): |
| 10 |
""" |
| 11 |
Create a new node. |
| 12 |
""" |
| 13 |
self.id = node_id |
| 14 |
self.alias = alias |
| 15 |
if isinstance(label, list): |
| 16 |
label = [inner_label for inner_label in label if inner_label != ""] |
| 17 |
|
| 18 |
if ( |
| 19 |
label is None |
| 20 |
or label == "" |
| 21 |
or (isinstance(label, list) and len(label) == 0) |
| 22 |
): |
| 23 |
self.label = None |
| 24 |
self.labels = None |
| 25 |
elif isinstance(label, str): |
| 26 |
self.label = label |
| 27 |
self.labels = [label] |
| 28 |
elif isinstance(label, list) and all( |
| 29 |
[isinstance(inner_label, str) for inner_label in label] |
| 30 |
): |
| 31 |
self.label = label[0] |
| 32 |
self.labels = label |
| 33 |
else: |
| 34 |
raise AssertionError( |
| 35 |
"label should be either None, string or a list of strings" |
| 36 |
) |
| 37 |
|
| 38 |
self.properties = properties or {} |
| 39 |
|
| 40 |
def to_string(self): |
| 41 |
res = "" |
| 42 |
if self.properties: |
| 43 |
props = ",".join( |
| 44 |
key + ":" + str(quote_string(val)) |
| 45 |
for key, val in sorted(self.properties.items()) |
| 46 |
) |
| 47 |
res += "{" + props + "}" |
| 48 |
|
| 49 |
return res |
| 50 |
|
| 51 |
def __str__(self): |
| 52 |
res = "(" |
| 53 |
if self.alias: |
| 54 |
res += self.alias |
| 55 |
if self.labels: |
| 56 |
res += ":" + ":".join(self.labels) |
| 57 |
if self.properties: |
| 58 |
props = ",".join( |
| 59 |
key + ":" + str(quote_string(val)) |
| 60 |
for key, val in sorted(self.properties.items()) |
| 61 |
) |
| 62 |
res += "{" + props + "}" |
| 63 |
res += ")" |
| 64 |
|
| 65 |
return res |
| 66 |
|
| 67 |
def __eq__(self, rhs): |
| 68 |
# Type checking |
| 69 |
if not isinstance(rhs, Node): |
| 70 |
return False |
| 71 |
|
| 72 |
# Quick positive check, if both IDs are set. |
| 73 |
if self.id is not None and rhs.id is not None and self.id != rhs.id: |
| 74 |
return False |
| 75 |
|
| 76 |
# Label should match. |
| 77 |
if self.label != rhs.label: |
| 78 |
return False |
| 79 |
|
| 80 |
# Quick check for number of properties. |
| 81 |
if len(self.properties) != len(rhs.properties): |
| 82 |
return False |
| 83 |
|
| 84 |
# Compare properties. |
| 85 |
if self.properties != rhs.properties: |
| 86 |
return False |
| 87 |
|
| 88 |
return True |