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"}},
        "host": "localhost",
        "port": 5432
    },
    "user_service": {
        "$reference": {"registry": {"schema": "user_service", "version": "1.0.0"}},
        "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"
            },
            "instance": "database"
        },
        "host": "localhost",
        "port": 5432
    },
    "user_service": {
        "$reference": {
            "registry": {
                "schema": "user_service",
                "version": "1.0.0"
            }
        },
        "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"}
            },
            "name": "Service 1"
        },
        "$service2"
    ]
}

Instance References

Reference other instances using the $ prefix:

{
    "cache": {
        "$reference": {"registry": {"schema": "cache", "version": "1.0.0"}, "instance": "cache"},
        "size": 1000
    },
    "service": {
        "$reference": {"registry": {"schema": "service", "version": "1.0.0"}},
        "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.4.tar.gz (66.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.4-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: modelmirror-0.1.4.tar.gz
  • Upload date:
  • Size: 66.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.4.tar.gz
Algorithm Hash digest
SHA256 ba452bd8cdc03eab5b257cf7be6172be4d4405dfeae4919521abc6da42ffb334
MD5 aee62cfe3be4022295f4631507fc0c88
BLAKE2b-256 ba2a3f6ffe6a74473bc05615595af9958d25ad0667696574146cce66f8b4b067

See more details on using hashes here.

File details

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

File metadata

  • Download URL: modelmirror-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 11.9 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.4-py3-none-any.whl
Algorithm Hash digest
SHA256 bddbae4d76619cbeaee84377872ed08d7b7e78a53bfe2fadb471cd5bd8a72b21
MD5 bd375b4b6660834c05982b38fbb23f85
BLAKE2b-256 35a00d22c7eebad934da39d74bb528cee4939061ad8c16876ebb472cac1852bb

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