Skip to main content

Global Object Factory for Python

Lightweight dependency injection for legacy code. Replace object instantiation with testable factories.

Installation

pip install global-object-factory

Breaking Hard Dependencies

Turn untestable legacy code into testable code by replacing direct instantiation with factory calls.

The Problem

Legacy code with hard dependencies:

class UserService:
    def process_user(self, user_id):
        # Hard to test - always hits real database
        repo = SqlRepository("server=prod;database=users")
        user = repo.get_user(user_id)
        return user

The Solution

Replace new with create():

from global_object_factory import create

class UserService:
    def process_user(self, user_id):
        # Now testable - can inject test doubles
        repo = create(SqlRepository)("server=prod;database=users")
        user = repo.get_user(user_id)
        return user

Writing Tests

Basic Test Setup

from global_object_factory import create, set_one, context

def test_user_service():
    # Create test double
    mock_repo = MockSqlRepository()
    mock_repo.users = {"123": User("John", "john@example.com")}

    with context():
        # Next create() call returns our mock
        set_one(SqlRepository, mock_repo)

        # Test the code
        service = UserService()
        user = service.process_user("123")

        assert user.name == "John"

Persistent Test Doubles

from global_object_factory import set_always, clear_one

def test_multiple_calls():
    mock_repo = MockSqlRepository()

    with context():
        # All create() calls return our mock
        set_always(SqlRepository, mock_repo)

        service = UserService()
        user1 = service.process_user("123")  # Uses mock
        user2 = service.process_user("456")  # Uses mock too

API Reference

Core Functions

  • create(cls) - Returns a factory function for the class
  • create_direct(cls, *args, **kwargs) - Create instance directly
  • set_one(cls, instance) - Return test double once, then normal instances
  • set_always(cls, instance) - Always return test double
  • clear_one(cls) - Clear test doubles for specific type
  • clear_all() - Clear all test doubles
  • context() - Context manager for automatic cleanup

Advanced Usage

Custom Factory Instance

from global_object_factory import ObjectFactory

# Create dedicated factory
api_factory = ObjectFactory()
create_api_service = api_factory.create(ApiService)
service = create_api_service("https://api.example.com")

Constructor Parameter Tracking

from global_object_factory.interfaces import IConstructorCalledWith, ConstructorParameterInfo
from typing import List

class TrackedService(IConstructorCalledWith):
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port
        self.constructor_params: List[ConstructorParameterInfo] = []

    def constructor_called_with(self, params: List[ConstructorParameterInfo]) -> None:
        self.constructor_params = params

# Usage
service = create(TrackedService)("localhost", 8080)
print(service.constructor_params[0].name)   # "host"
print(service.constructor_params[0].value)  # "localhost"

Object Registration

from global_object_factory import register_object, get_registered_object

config = DatabaseConfig()
object_id = register_object(config, "db-config")

# Later retrieve it
retrieved = get_registered_object("db-config")

Requirements

  • Python 3.8+
  • typing-extensions (for Python < 3.10)

License

PolyForm Noncommercial License 1.0.0

Metadata

Release files for global-object-factory 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for global-object-factory 1.0.1
File Size Uploaded Provenance Actions
global_object_factory-1.0.1.tar.gz 15.9 kB Without provenance Details for global_object_factory-1.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for global-object-factory 1.0.1
File Interpreter ABI Platform Actions
global_object_factory-1.0.1-py3-none-any.whl Python 3 none any Details for global_object_factory-1.0.1-py3-none-any.whl

Total release size: 26.9 kB

Release files / global_object_factory-1.0.1.tar.gz

Download URL global_object_factory-1.0.1.tar.gz
Size 15.9 kB
Tags Source
SHA-256 checksum
How to use checksums
3e7acc7a0d2a4e7c7d921e67ff5822bb1a7a0cda17243e1b4c2696db527dedfd
BLAKE2b-256 checksum
How to use checksums
0d464c460633805914a4ee8f560e0488d2f6a832064b8da9fce4b3cbd8cb372c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Release files / global_object_factory-1.0.1-py3-none-any.whl

Download URL global_object_factory-1.0.1-py3-none-any.whl
Size 11.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0d904ef602ab078bd3c16c59e9d966fa4deb89e483103ded4e8f8efd32ddc0e7
BLAKE2b-256 checksum
How to use checksums
275263668415e73bf7b7b01063825dde5069fbd0fbed7b4ae9d31dfa0aee6d08
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Security for global-object-factory 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page