🔍 Code Extractor

function get_model_class

Maturity: 53

Retrieves a model class from a registry by its string name, returning the class type or None if not found.

File:
/tf/active/vicechatdev/CDocs/models/__init__.py
Lines:
86 - 96
Complexity:
simple

Purpose

This function provides a lookup mechanism to dynamically retrieve model classes from a centralized registry (_model_registry). It's useful for scenarios where model classes need to be instantiated or referenced based on string identifiers, such as in factory patterns, configuration-driven model selection, or plugin architectures. The function is part of a model registry system that likely manages various document-related models including users, documents, reviews, and approvals.

Source Code

def get_model_class(name: str) -> Optional[Type[BaseModel]]:
    """
    Get a model class by name.
    
    Args:
        name: Name of the model class
        
    Returns:
        Model class or None if not found
    """
    return _model_registry.get(name)

Parameters

Name Type Default Kind
name str - positional_or_keyword

Parameter Details

name: A string identifier representing the name of the model class to retrieve. This should match a key in the _model_registry dictionary. Expected values would be model class names like 'DocUser', 'ControlledDocument', 'DocumentVersion', 'ReviewCycle', 'ReviewComment', or 'ApprovalCycle'. The lookup is case-sensitive and must match the exact registration name.

Return Value

Type: Optional[Type[BaseModel]]

Returns an Optional[Type[BaseModel]], which means it either returns a class type that inherits from BaseModel, or None if no model with the given name exists in the registry. The returned value is a class type itself (not an instance), allowing the caller to instantiate it or inspect its properties. If the name is not found in _model_registry, the function returns None rather than raising an exception.

Dependencies

  • typing
  • logging

Required Imports

from typing import Optional, Type
from CDocs.models.user_extensions import DocUser
from CDocs.models.document import ControlledDocument
from CDocs.models.document import DocumentVersion
from CDocs.models.review import ReviewCycle
from CDocs.models.review import ReviewComment
from CDocs.models.approval import ApprovalCycle

Usage Example

# Assuming _model_registry is populated and the function is imported
from your_module import get_model_class

# Retrieve a model class by name
DocUserClass = get_model_class('DocUser')

if DocUserClass is not None:
    # Instantiate the model class
    user = DocUserClass(username='john_doe', email='john@example.com')
    print(f"Created user: {user}")
else:
    print("Model class not found")

# Try to get a non-existent model
UnknownModel = get_model_class('NonExistentModel')
if UnknownModel is None:
    print("Model not found in registry")

# Use in a factory pattern
def create_model_instance(model_name: str, **kwargs):
    ModelClass = get_model_class(model_name)
    if ModelClass:
        return ModelClass(**kwargs)
    raise ValueError(f"Unknown model: {model_name}")

document = create_model_instance('ControlledDocument', title='My Document', version='1.0')

Best Practices

  • Always check if the returned value is None before attempting to use the model class to avoid AttributeError
  • Ensure _model_registry is properly initialized and populated before calling this function
  • Use consistent naming conventions when registering models to avoid lookup failures
  • Consider implementing a get_all_model_names() companion function to discover available models
  • For production code, consider adding logging when a model is not found to aid debugging
  • If the registry might be modified at runtime, ensure thread-safety when accessing _model_registry
  • Document which model names are available in the registry for API consumers

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function register_model 73.4% similar

    Registers a model class in a global registry dictionary, enabling dynamic model lookup and management. Can be used as a decorator or called directly.

    From: /tf/active/vicechatdev/CDocs/models/__init__.py
  • function get_all_model_classes 70.0% 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
  • function get_logger 46.7% similar

    A wrapper function that retrieves a logger instance from Python's logging module with the specified name.

    From: /tf/active/vicechatdev/contract_validity_analyzer/utils/logging_utils.py
  • class BaseModel 43.9% similar

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

    From: /tf/active/vicechatdev/CDocs/models/__init__.py
  • function get_document_type_name 41.5% similar

    Looks up and returns the full document type name corresponding to a given document type code by searching through a DOCUMENT_TYPES dictionary.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
← Back to Browse