图片解析应用
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.

91 lines
2.4 KiB

  1. from ..helpers import quote_string
  2. from .node import Node
  3. class Edge:
  4. """
  5. An edge connecting two nodes.
  6. """
  7. def __init__(self, src_node, relation, dest_node, edge_id=None, properties=None):
  8. """
  9. Create a new edge.
  10. """
  11. if src_node is None or dest_node is None:
  12. # NOTE(bors-42): It makes sense to change AssertionError to
  13. # ValueError here
  14. raise AssertionError("Both src_node & dest_node must be provided")
  15. self.id = edge_id
  16. self.relation = relation or ""
  17. self.properties = properties or {}
  18. self.src_node = src_node
  19. self.dest_node = dest_node
  20. def to_string(self):
  21. res = ""
  22. if self.properties:
  23. props = ",".join(
  24. key + ":" + str(quote_string(val))
  25. for key, val in sorted(self.properties.items())
  26. )
  27. res += "{" + props + "}"
  28. return res
  29. def __str__(self):
  30. # Source node.
  31. if isinstance(self.src_node, Node):
  32. res = str(self.src_node)
  33. else:
  34. res = "()"
  35. # Edge
  36. res += "-["
  37. if self.relation:
  38. res += ":" + self.relation
  39. if self.properties:
  40. props = ",".join(
  41. key + ":" + str(quote_string(val))
  42. for key, val in sorted(self.properties.items())
  43. )
  44. res += "{" + props + "}"
  45. res += "]->"
  46. # Dest node.
  47. if isinstance(self.dest_node, Node):
  48. res += str(self.dest_node)
  49. else:
  50. res += "()"
  51. return res
  52. def __eq__(self, rhs):
  53. # Type checking
  54. if not isinstance(rhs, Edge):
  55. return False
  56. # Quick positive check, if both IDs are set.
  57. if self.id is not None and rhs.id is not None and self.id == rhs.id:
  58. return True
  59. # Source and destination nodes should match.
  60. if self.src_node != rhs.src_node:
  61. return False
  62. if self.dest_node != rhs.dest_node:
  63. return False
  64. # Relation should match.
  65. if self.relation != rhs.relation:
  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