图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.3 KiB

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