🔍 Code Extractor

class BaseModel

Maturity: 48

Base class providing common data model functionality for all models in the system, including property management, serialization, and deserialization.

File:
/tf/active/vicechatdev/CDocs/models/__init__.py
Lines:
17 - 67
Complexity:
simple

Purpose

BaseModel serves as the foundation for all data models in the CDocs system. It provides a standardized interface for managing model data through a dictionary-based storage system, with built-in support for property access, updates, and conversion to/from dictionary representations. This class is designed to be inherited by specific model classes like ControlledDocument, DocumentVersion, ReviewCycle, etc., providing them with consistent data handling capabilities.

Source Code

class BaseModel:
    """Base class for all data models in the system."""
    
    def __init__(self, data: Optional[Dict[str, Any]] = None):
        """
        Initialize model with optional data.
        
        Args:
            data: Dictionary containing initial property values
        """
        self._data = data or {}
        
    @property
    def uid(self) -> Optional[str]:
        """Get the unique identifier for this model."""
        return self._data.get('UID')
        
    @property
    def properties(self) -> Dict[str, Any]:
        """Get all properties of this model."""
        return self._data.copy()
        
    def update(self, properties: Dict[str, Any]) -> bool:
        """
        Update model properties.
        
        Args:
            properties: Properties to update
            
        Returns:
            Boolean indicating whether update was successful
        """
        self._data.update(properties)
        return True
        
    def to_dict(self) -> Dict[str, Any]:
        """Convert model to dictionary representation."""
        return self._data.copy()
        
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'BaseModel':
        """
        Create model instance from dictionary.
        
        Args:
            data: Dictionary containing property values
            
        Returns:
            Instance of the model class
        """
        return cls(data)

Parameters

Name Type Default Kind
bases - -

Parameter Details

data: Optional dictionary containing initial property values for the model. Keys are property names (strings) and values can be of any type. If not provided or None, an empty dictionary is used. The 'UID' key is treated specially as the unique identifier for the model instance.

Return Value

Instantiation returns a BaseModel instance with internal data storage initialized. The uid property returns an optional string (the 'UID' value or None). The properties property returns a copy of all stored data as a dictionary. The update method returns a boolean (always True in this implementation). The to_dict method returns a dictionary copy of all model data. The from_dict class method returns a new instance of the model class.

Class Interface

Methods

__init__(self, data: Optional[Dict[str, Any]] = None)

Purpose: Initialize the model instance with optional initial data

Parameters:

  • data: Optional dictionary containing initial property values. Defaults to empty dict if None.

Returns: None (constructor)

@property uid(self) -> Optional[str] property

Purpose: Get the unique identifier for this model instance

Returns: String containing the UID if present in data, otherwise None

@property properties(self) -> Dict[str, Any] property

Purpose: Get a copy of all properties stored in this model

Returns: Dictionary containing all model properties (a copy, not the original)

update(self, properties: Dict[str, Any]) -> bool

Purpose: Update the model's properties with new values, merging with existing data

Parameters:

  • properties: Dictionary of properties to update. Keys are property names, values are the new values to set.

Returns: Boolean indicating success (always True in base implementation)

to_dict(self) -> Dict[str, Any]

Purpose: Convert the model to a dictionary representation for serialization

Returns: Dictionary containing all model data (a copy, not the original)

@classmethod from_dict(cls, data: Dict[str, Any]) -> 'BaseModel'

Purpose: Create a new model instance from a dictionary (factory method)

Parameters:

  • data: Dictionary containing property values to initialize the new instance

Returns: New instance of the model class (or subclass) initialized with the provided data

Attributes

Name Type Description Scope
_data Dict[str, Any] Internal dictionary storing all model properties and values. Should be treated as private. instance

Dependencies

  • typing

Required Imports

from typing import Dict, Any, Optional

Usage Example

# Basic instantiation
model = BaseModel()

# Instantiation with initial data
model = BaseModel({'UID': '12345', 'name': 'Test Model', 'status': 'active'})

# Access unique identifier
uid = model.uid  # Returns '12345'

# Get all properties
all_props = model.properties  # Returns copy of all data

# Update properties
model.update({'status': 'inactive', 'updated_at': '2024-01-01'})

# Convert to dictionary
data_dict = model.to_dict()

# Create from dictionary
new_model = BaseModel.from_dict({'UID': '67890', 'name': 'Another Model'})

# Typical subclass usage
class User(BaseModel):
    @property
    def name(self):
        return self._data.get('name')

user = User({'UID': 'user123', 'name': 'John Doe'})
print(user.name)  # 'John Doe'
print(user.uid)   # 'user123'

Best Practices

  • This class is designed to be inherited, not used directly. Create subclasses that extend BaseModel with domain-specific properties and methods.
  • The internal _data dictionary should not be accessed directly outside the class. Use the provided properties and methods instead.
  • The properties and to_dict methods return copies of the internal data to prevent external modification of the internal state.
  • When subclassing, add @property decorators for specific fields to provide type-safe access to model attributes.
  • The update method always returns True in this implementation. Subclasses may override this to add validation logic.
  • The 'UID' key is reserved for the unique identifier. Ensure this is set when creating instances that need identification.
  • Use from_dict class method for creating instances from serialized data (e.g., from database or API responses).
  • The model is stateful - all changes via update() modify the internal _data dictionary permanently.
  • Thread safety is not guaranteed - if using in multi-threaded environments, implement appropriate locking mechanisms in subclasses.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class Document 62.1% similar

    A dataclass representing a document with hierarchical structure, versioning, metadata, and collaboration features.

    From: /tf/active/vicechatdev/vice_ai/models.py
  • class ControlledDocument 57.4% similar

    Model representing a controlled document.

    From: /tf/active/vicechatdev/CDocs/models/document.py
  • class BaseCleaner 57.1% similar

    Abstract base class that defines the interface for document cleaning implementations, providing methods to remove redundancy from document collections and track cleaning statistics.

    From: /tf/active/vicechatdev/chromadb-cleanup/src/cleaners/base_cleaner.py
  • function get_all_model_classes 56.3% similar

    Retrieves a copy of the internal model registry containing all registered model classes mapped by their names.

    From: /tf/active/vicechatdev/CDocs/models/__init__.py
  • class ComplexDocument 53.3% similar

    A class representing a complex document with multiple sections, supporting section management, references, metadata, and serialization capabilities.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
← Back to Browse