class _Relationship
A class representing a graph relationship (edge) with labels, properties, and an optional element ID, inheriting from PropertyDict to manage key-value properties.
/tf/active/vicechatdev/neo4j_driver/neo4j_objects.py
240 - 289
moderate
Purpose
This class models a relationship in a graph database structure, storing labels (relationship types), properties (key-value pairs), and an optional element_id for database identification. It provides property-based access to labels and element_id with validation, and custom string representations for debugging and display. The class is designed to work with graph database systems where relationships connect nodes and have typed labels and arbitrary properties.
Source Code
class _Relationship(PropertyDict):
def __init__(self, *labels, _element_id=None, **properties):
self._labels = set(labels)
if _element_id is None:
self._element_id = None
else:
try:
self._element_id = int(_element_id)
except ValueError:
raise ValueError(f"element_id must be an integer or None, got {_element_id}")
PropertyDict.__init__(self, properties)
@property
def labels(self):
return set(self._labels)
@labels.setter
def labels(self, labels):
if isinstance(labels, list):
self._labels=labels
elif isinstance(labels, str):
self._labels=[labels]
else:
raise ValueError("Please pass a list or string as label")
@property
def element_id(self):
return self._element_id
@element_id.setter
def element_id(self, x):
try:
int(x)
except:
raise ValueError("Invalid input for element_id, value cannot be coerced to int")
self._element_id = x
def __str__(self):
kwargs = dict(self)
labels_str = ", ".join(self.labels)
props_str = ", ".join("{}: {!r}".format(k, v) for k, v in kwargs.items())
return "[{} {{ {} }}]".format(labels_str, props_str)
def __repr__(self):
kwargs = dict(self)
labels_str = ", ".join(self.labels)
props_str = ", ".join("{}={!r}".format(k, v) for k, v in kwargs.items())
return "[{}, {}]".format(labels_str, props_str)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
PropertyDict | - |
Parameter Details
*labels: Variable number of string arguments representing the relationship type labels. These are stored as a set internally to ensure uniqueness. Can be zero or more label strings.
_element_id: Optional keyword-only parameter representing the database element identifier. Must be convertible to an integer or None. Used to track the relationship's identity in a graph database. Defaults to None for new relationships not yet persisted.
**properties: Arbitrary keyword arguments representing property key-value pairs for the relationship. These are passed to the parent PropertyDict class and can be accessed like dictionary items.
Return Value
Instantiation returns a _Relationship object that behaves like a dictionary for properties while maintaining labels and element_id as separate managed attributes. The __str__ method returns a formatted string like '[label1, label2 { prop1: value1, prop2: value2 }]'. The __repr__ method returns a similar representation suitable for debugging.
Class Interface
Methods
__init__(self, *labels, _element_id=None, **properties)
Purpose: Initialize a relationship with labels, optional element ID, and properties
Parameters:
*labels: Variable number of label strings for the relationship type_element_id: Optional integer identifier for the relationship in the database (default: None)**properties: Arbitrary keyword arguments for relationship properties
Returns: None (constructor)
@property labels(self) -> set
property
Purpose: Get a copy of the relationship's labels as a set
Returns: A set containing all label strings for this relationship
@labels.setter labels(self, labels)
property
Purpose: Set the relationship's labels from a list or string
Parameters:
labels: Either a list of label strings or a single label string
Returns: None (setter)
@property element_id(self) -> int | None
property
Purpose: Get the relationship's database element identifier
Returns: Integer element ID or None if not set
@element_id.setter element_id(self, x)
property
Purpose: Set the relationship's element ID with validation
Parameters:
x: Value that can be coerced to an integer
Returns: None (setter)
__str__(self) -> str
Purpose: Return a human-readable string representation of the relationship
Returns: Formatted string like '[label1, label2 { prop1: value1, prop2: value2 }]'
__repr__(self) -> str
Purpose: Return a detailed string representation suitable for debugging
Returns: Formatted string like '[label1, label2, prop1=value1, prop2=value2]'
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
_labels |
set | list | Internal storage for relationship labels, initially a set but can become a list via setter | instance |
_element_id |
int | None | Internal storage for the database element identifier, validated to be integer or None | instance |
Required Imports
from uuid import uuid4
from itertools import chain
import warnings
Usage Example
# Create a relationship with labels and properties
rel = _Relationship('KNOWS', 'FRIEND_OF', _element_id=123, since=2020, strength=0.8)
# Access labels
print(rel.labels) # {'KNOWS', 'FRIEND_OF'}
# Modify labels
rel.labels = ['WORKS_WITH', 'COLLEAGUE']
# Access properties (inherited from PropertyDict)
print(rel['since']) # 2020
rel['verified'] = True
# Access element_id
print(rel.element_id) # 123
# Update element_id
rel.element_id = 456
# String representation
print(str(rel)) # [WORKS_WITH, COLLEAGUE { since: 2020, strength: 0.8, verified: True }]
print(repr(rel)) # [WORKS_WITH, COLLEAGUE, since=2020, strength=0.8, verified=True]
Best Practices
- Always pass _element_id as a keyword argument (with underscore prefix) to avoid confusion with labels
- The element_id should be set by the database system after persistence; use None for new relationships
- Labels are stored as a set internally but the setter converts lists and strings appropriately
- When setting labels via the property setter, pass either a list of strings or a single string
- Properties can be accessed and modified using dictionary-style syntax (inherited from PropertyDict)
- The class maintains immutability of the original labels set by returning a copy via the labels property getter
- Element_id must be convertible to an integer; attempting to set non-numeric values will raise ValueError
- Use __str__ for human-readable output and __repr__ for debugging/logging purposes
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class Relationship 79.2% similar
-
class Node 69.3% similar
-
class ManualRelationshipManager 58.5% similar
-
class Graph 57.6% similar
-
class RelTypes 57.5% similar