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.3.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.3-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: modelmirror-0.1.3.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.3.tar.gz
Algorithm Hash digest
SHA256 d0229a7fc7f8aa7cf60a922a35b4efcc58dee2bfcb0bd3560528043f6b20b4bf
MD5 ff7018689fce23d98b7e5e468c77f16d
BLAKE2b-256 1137a7c0b138bda8f56decca3ec00166170335316a2f1ac5ff3c3ca31daa1486

See more details on using hashes here.

File details

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

File metadata

  • Download URL: modelmirror-0.1.3-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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 66aa63db7b5a656f034d024ea3d1db340e3bf140c6d7d899aa91ad979c97e89f
MD5 62eb7d4a44361197771463b970d30c28
BLAKE2b-256 654c1203e3b0a795b134fc782b35ef73f4d56114daf0857fc047019d847cfc18

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