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"}, "instance": "database"},
        "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.5.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.5-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: modelmirror-0.1.5.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.5.tar.gz
Algorithm Hash digest
SHA256 85b9b2130615cb44426682804736787d5f5de923097e067a4f00f12748b059ae
MD5 60edb7593c5673c81503f27b5db67f78
BLAKE2b-256 4a1eb3a49233c87005f5a22e3ca11ddcf07ebc5613db162cfb205aa92392d17b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: modelmirror-0.1.5-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.5-py3-none-any.whl
Algorithm Hash digest
SHA256 16ad0758309befc80edefd0acdc2af5cd992beda1333a14ff3dba1f14c3a1068
MD5 207c8b40fc39c4f3e22ccbcb1b4a7e4a
BLAKE2b-256 9281c1afc30998fad8551db7e0a1b35bca518090f77d3119e23dedea46190c5b

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