Skip to main content

Model Mirror

Project description

ModelMirror

A Python library for dependency injection and configuration management using JSON files. ModelMirror allows you to define object instances and their dependencies in JSON configuration files, then automatically instantiate and wire them together at runtime.

Quick Example

from modelmirror.mirror import Mirror
from modelmirror.class_provider.class_register import ClassRegister
from modelmirror.class_provider.class_reference import ClassReference

# Define your classes
class DatabaseService:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port

class UserService:
    def __init__(self, db: DatabaseService, cache_enabled: bool):
        self.db = db
        self.cache_enabled = cache_enabled

# Register classes - schema and version must match the $reference in JSON config
class DatabaseServiceRegister(ClassRegister,
    reference=ClassReference(
        schema="database",
        version="1.0.0",
        cls=DatabaseService
    )):
    pass

class UserServiceRegister(ClassRegister,
    reference=ClassReference(
        schema="user_service",
        version="1.0.0",
        cls=UserService
    )):
    pass

# Define configuration in JSON
config = {
    "database": {
        "$reference": {"registry": {"schema": "database", "version": "1.0.0"}},
        "params": {"host": "localhost", "port": 5432}
    },
    "user_service": {
        "$reference": {"registry": {"schema": "user_service", "version": "1.0.0"}},
        "params": {"db": "$database", "cache_enabled": True}
    }
}

# Load and instantiate
mirror = Mirror('myapp')
instances = mirror.reflect_raw('config.json')
user_service = instances.get(UserService)

Features

  • JSON-based Configuration: Define object instances and dependencies in JSON files
  • Automatic Dependency Injection: Reference instances using $instance_name syntax
  • Non-Intrusive: Works with existing classes without modification - no need to change your code
  • Simple Registration: Register any class by creating a simple registry entry
  • Type Safety: Integration with Pydantic for validation and type checking
  • Class Registration: Register classes with schema and version
  • Dependency Resolution: Automatic topological sorting of dependencies
  • Multiple Instance Types: Support for single instances, lists, and dictionaries

Installation

pip install modelmirror

Usage

1. Register Your Classes

Create class registers that define how your classes should be instantiated:

from modelmirror.class_provider.class_register import ClassRegister
from modelmirror.class_provider.class_reference import ClassReference

class DatabaseServiceRegister(ClassRegister,
    reference=ClassReference(
        schema="database",
        version="1.0.0",
        cls=DatabaseService
    )):
    pass

class UserServiceRegister(ClassRegister,
    reference=ClassReference(
        schema="user_service",
        version="1.0.0",
        cls=UserService
    )):
    pass

2. Create JSON Configuration

Define your instances and their dependencies in a JSON file:

{
    "database": {
        "$reference": {
            "registry": {
                "schema": "database",
                "version": "1.0.0"
            }
        },
        "params": {
            "host": "localhost",
            "port": 5432
        }
    },
    "user_service": {
        "$reference": {
            "registry": {
                "schema": "user_service",
                "version": "1.0.0"
            }
        },
        "params": {
            "db": "$database",
            "cache_enabled": true
        }
    }
}

3. Load Configuration

Use the Mirror class to load and instantiate your objects:

from modelmirror.mirror import Mirror

# Load configuration and get instances
mirror = Mirror('myapp')  # Package name where registers are defined
instances = mirror.reflect_raw('config.json')

# Get specific instances
database = instances.get(DatabaseService)
user_service = instances.get(UserService)

# Get instance by ID
database = instances.get(DatabaseService, 'database')

4. Type-Safe Configuration with Pydantic

Define a Pydantic model for type-safe configuration loading:

from pydantic import BaseModel

class AppConfig(BaseModel):
    database: DatabaseService
    user_service: UserService

# Load with type validation
config = mirror.reflect_typed('config.json', AppConfig)
print(config.database.host)  # Type-safe access

Advanced Features

Lists and Collections

{
    "services": [
        {
            "$reference": {
                "instance": "service1",
                "registry": {"schema": "service", "version": "1.0.0"}
            },
            "params": {"name": "Service 1"}
        },
        "$service2"
    ]
}

Instance References

Reference other instances using the $ prefix:

{
    "cache": {
        "$reference": {"registry": {"schema": "cache", "version": "1.0.0"}},
        "params": {"size": 1000}
    },
    "service": {
        "$reference": {"registry": {"schema": "service", "version": "1.0.0"}},
        "params": {
            "cache": "$cache",
            "timeout": 30
        }
    }
}

Requirements

  • Python >= 3.10
  • Pydantic >= 2.0.0

Development

# Install development dependencies
pip install -e ".[dev]"

# Run tests
python -m pytest tests/

# Run pre-commit hooks
pre-commit run --all-files

License

MIT License - see LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

modelmirror-0.1.2.tar.gz (65.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

modelmirror-0.1.2-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

Details for the file modelmirror-0.1.2.tar.gz.

File metadata

  • Download URL: modelmirror-0.1.2.tar.gz
  • Upload date:
  • Size: 65.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for modelmirror-0.1.2.tar.gz
Algorithm Hash digest
SHA256 9a8cee45fdd5e251f333470631de97ddb379626cc305c972829812db032d1a73
MD5 6dea1587f52dcf78d02daa1a5b50977d
BLAKE2b-256 4f5d262aa453f2460b3b046220fee495c07cc1d799d48562648949cc88e0fde2

See more details on using hashes here.

File details

Details for the file modelmirror-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: modelmirror-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 11.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for modelmirror-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 350ad404ba059d4a8ba8ee759b72c0aed6a0b232fa0d839c004232c613ae384e
MD5 caa9998777be94c4fc878ca3a0818799
BLAKE2b-256 3ae0a97f519a2c376f4a296fecbee8a3c49a3443d2645b31a0edd538321b8965

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page