Global Object Factory for Python - Lightweight dependency injection for legacy code
Project description
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 classcreate_direct(cls, *args, **kwargs)- Create instance directlyset_one(cls, instance)- Return test double once, then normal instancesset_always(cls, instance)- Always return test doubleclear_one(cls)- Clear test doubles for specific typeclear_all()- Clear all test doublescontext()- 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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file global_object_factory-1.0.0.tar.gz.
File metadata
- Download URL: global_object_factory-1.0.0.tar.gz
- Upload date:
- Size: 15.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e87e1c5b9c51f28833062d0634b0a5c8a77ac4a8ef85036294e5456bd7af966f
|
|
| MD5 |
f9f8049c5a6902a8bfe8920b7c70916e
|
|
| BLAKE2b-256 |
1ed0761203ec20ac81f576cbbe216668c500b68e543d44afec0439ccf89066e1
|
File details
Details for the file global_object_factory-1.0.0-py3-none-any.whl.
File metadata
- Download URL: global_object_factory-1.0.0-py3-none-any.whl
- Upload date:
- Size: 11.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5c5cbb2f5d397d35388d95488389ca3bc833d2e2c5d2fc792cdd7b91d00795d5
|
|
| MD5 |
4b696546e49942e6fc90561cda86d4fc
|
|
| BLAKE2b-256 |
baa608908d137be3aeb118385ccc196b760e2ae96dae13e8d066614546039456
|