function _sanitize_properties
Sanitizes a dictionary of properties to ensure compatibility with Neo4j by converting complex objects to primitive types, extracting UIDs from DocUser objects, and preserving datetime objects.
/tf/active/vicechatdev/CDocs/db/db_operations.py
21 - 39
simple
Purpose
This function prepares property dictionaries for storage in Neo4j graph database by converting incompatible Python objects into Neo4j-compatible types. It handles special cases like DocUser objects (extracts UID), datetime objects (preserves as-is), and other complex objects (converts to string representation). This ensures data can be safely stored as node or relationship properties in Neo4j without type errors.
Source Code
def _sanitize_properties(properties: Dict[str, Any]) -> Dict[str, Any]:
"""
Sanitize properties to ensure they're compatible with Neo4j.
Converts objects to their string representation or UID where appropriate.
"""
sanitized = {}
for key, value in properties.items():
# Handle DocUser objects - extract UID
if hasattr(value, 'uid') and hasattr(value, '__class__') and 'DocUser' in str(value.__class__):
sanitized[key] = value.uid
# Handle datetime objects
elif isinstance(value, datetime):
sanitized[key] = value
# Handle other complex objects by converting to string
elif hasattr(value, '__dict__') and not isinstance(value, (str, int, float, bool, list, dict)):
sanitized[key] = str(value)
else:
sanitized[key] = value
return sanitized
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
properties |
Dict[str, Any] | - | positional_or_keyword |
Parameter Details
properties: A dictionary containing key-value pairs representing properties to be stored in Neo4j. Keys are strings representing property names. Values can be of any type including primitive types (str, int, float, bool), collections (list, dict), datetime objects, or custom objects like DocUser. The function will sanitize values to ensure Neo4j compatibility.
Return Value
Type: Dict[str, Any]
Returns a new dictionary with the same keys as the input, but with values converted to Neo4j-compatible types. DocUser objects are replaced with their UID attribute, datetime objects are preserved, complex custom objects are converted to their string representation, and primitive types (str, int, float, bool, list, dict) are passed through unchanged.
Dependencies
datetime
Required Imports
from typing import Dict, Any
from datetime import datetime
Usage Example
from typing import Dict, Any
from datetime import datetime
def _sanitize_properties(properties: Dict[str, Any]) -> Dict[str, Any]:
sanitized = {}
for key, value in properties.items():
if hasattr(value, 'uid') and hasattr(value, '__class__') and 'DocUser' in str(value.__class__):
sanitized[key] = value.uid
elif isinstance(value, datetime):
sanitized[key] = value
elif hasattr(value, '__dict__') and not isinstance(value, (str, int, float, bool, list, dict)):
sanitized[key] = str(value)
else:
sanitized[key] = value
return sanitized
# Example usage
class DocUser:
def __init__(self, uid, name):
self.uid = uid
self.name = name
class CustomObject:
def __init__(self, value):
self.value = value
def __str__(self):
return f"CustomObject({self.value})"
user = DocUser("user123", "John Doe")
properties = {
"name": "Document",
"count": 42,
"active": True,
"created_at": datetime(2024, 1, 15, 10, 30),
"owner": user,
"metadata": CustomObject("test"),
"tags": ["tag1", "tag2"]
}
sanitized = _sanitize_properties(properties)
print(sanitized)
# Output: {'name': 'Document', 'count': 42, 'active': True, 'created_at': datetime(2024, 1, 15, 10, 30), 'owner': 'user123', 'metadata': 'CustomObject(test)', 'tags': ['tag1', 'tag2']}
Best Practices
- Always call this function before storing properties in Neo4j to avoid type compatibility errors
- Ensure DocUser objects have a 'uid' attribute if they will be passed to this function
- Be aware that complex objects are converted to strings, which may lose structured data - consider serializing to JSON if structure needs to be preserved
- The function creates a new dictionary rather than modifying the input, preserving the original data
- Datetime objects are preserved as-is, which requires Neo4j 3.4+ for native datetime support
- Lists and dictionaries are passed through unchanged - ensure nested objects within them are also compatible with Neo4j
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function update_node 57.8% similar
-
function clean_for_json_v9 55.3% similar
-
function push_changes 54.8% similar
-
function clean_for_json_v12 54.7% similar
-
function clean_for_json_v10 54.7% similar