🔍 Code Extractor

function _sanitize_properties

Maturity: 51

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.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
21 - 39
Complexity:
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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function update_node 57.8% similar

    Updates properties of a Neo4j graph database node identified by its unique UID, automatically adding a modification timestamp.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function clean_for_json_v9 55.3% similar

    Recursively sanitizes Python objects (dicts, lists, floats) to ensure they are JSON-serializable by converting NaN and infinity values to None and ensuring all dictionary keys are strings.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/c385e1f5-fbf6-4832-8fd4-78ef8b72fc53/project_2/analysis.py
  • function push_changes 54.8% similar

    Updates a node's properties in a Neo4j graph database by matching on UID and setting new property values.

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • function clean_for_json_v12 54.7% similar

    Recursively sanitizes Python objects to make them JSON-serializable by converting non-serializable types (NumPy types, pandas objects, tuples, NaN/Inf values) into JSON-compatible formats.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/290a39ea-3ae0-4301-8e2f-9d5c3bf80e6e/project_3/analysis.py
  • function clean_for_json_v10 54.7% similar

    Recursively converts Python objects containing NumPy and Pandas data types into JSON-serializable native Python types.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/c385e1f5-fbf6-4832-8fd4-78ef8b72fc53/project_1/analysis.py
← Back to Browse