Skip to main content

A comprehensive Python factory pattern implementation with thread-safe operations and type-safe generics

Project description

Sweet Tea Factory System

CI PyPI version Python 3.10+ codecov License

A comprehensive, production-ready Python dependency injection framework using factory patterns with configuration-based object management and lifecycle control.

🚀 Features

  • Configuration-Based Dependency Injection: Register classes once, create instances with runtime configuration
  • Dual Factory Patterns: Class-based factories (new instances) AND instance-based singletons (shared instances)
  • Thread-Safe Registry: Concurrent operations with RLock synchronization
  • Type-Safe Generics: Full TypeVar support with __class_getitem__
  • Flexible Key Matching: Support for ClassName, class_name, classname variations
  • Optional Dependencies: Graceful handling with custom warnings
  • Auto-Registration: Classes automatically registered via package imports
  • Lazy Singletons: SingletonFactory.create() for on-demand singleton instantiation
  • Comprehensive Testing: 58 tests with 97% coverage
  • Rich Documentation: MkDocs with Dracula theme and API reference

🏗️ Dependency Injection

Sweet Tea provides a powerful configuration-based dependency injection system that separates object creation from usage:

Service Registration

# Register services once at application startup
Registry.register("database", PostgreSQLConnection)
Registry.register("cache", RedisCache)
Registry.register("email", SMTPEmailService)

Constructor Injection with Factories

# Inject factories into constructors for on-demand dependency creation
class UserService:
    def __init__(self, db_factory, cache_factory):
        self.db_factory = db_factory  # Store factory reference
        self.cache_factory = cache_factory

    def get_user(self, user_id):
        # Create database connection when needed
        db = self.db_factory.create("database", configuration={
            "host": "prod-db",
            "port": 5432,
            "credentials": {...}
        })

        # Create cache when needed
        cache = self.cache_factory.create("cache", configuration={
            "host": "redis-cluster",
            "ttl": 3600
        })

        # Use dependencies...
        user_data = db.query(f"SELECT * FROM users WHERE id = {user_id}")
        cached_user = cache.get(f"user:{user_id}")
        return user_data or cached_user

Direct Dependency Injection

# Traditional approach: inject pre-configured instances
class UserService:
    def __init__(self, database, cache):
        self.database = database  # Pre-configured instance
        self.cache = cache        # Pre-configured instance

Lifecycle Management

# Singletons for shared resources
auth_service = SingletonFactory.create("auth", configuration={"jwt_secret": "..."})
# Same instance returned on subsequent calls

# New instances for request-scoped objects
request_handler = Factory.create("request_handler", configuration={"user_id": 123})
# Fresh instance for each request

Benefits

  • Separation of Concerns: Configuration separate from implementation
  • Testability: Easy mocking and dependency substitution
  • Flexibility: Runtime configuration changes without code changes
  • Maintainability: Centralized dependency management
  • Type Safety: Compile-time interface checking with AbstractFactory

📦 Installation

Using uv (Recommended)

uv add sweet-tea

Using pip

pip install sweet-tea

Using Poetry

poetry add sweet-tea

🏁 Quick Start

from sweet_tea import Registry, Factory, AbstractFactory, SingletonFactory

# === CLASS-BASED FACTORY (Creates new instances each time) ===
Registry.register("database", DatabaseConnection)
db1 = Factory.create("database", configuration={"host": "server1"})
db2 = Factory.create("database", configuration={"host": "server2"})
# db1 ≠ db2 (different instances)

# === LAZY SINGLETON FACTORY (Creates and caches instances on-demand) ===
Registry.register("database", DatabaseConnection)
db3 = SingletonFactory.create("database", configuration={"host": "prod-db", "pool_size": 10})
db4 = SingletonFactory.create("database")  # Returns cached instance
# db3 === db4 (same cached instance)

# === TYPE-SAFE ABSTRACT FACTORIES ===
class DatabaseInterface:
    def connect(self) -> str: ...

db_factory = AbstractFactory[DatabaseInterface]
db = db_factory.create("postgres")  # Only classes implementing DatabaseInterface

Three Factory Patterns

  1. Factory - Class registration → New instances with configuration
  2. AbstractFactory - Type-constrained → New instances with type safety
  3. SingletonFactory - Lazy singletons → Cached instances created on-demand

📖 Documentation

Complete documentation is available at https://snoodleboot-io.github.io/sweet_tea/

User Guides

API Reference

Development

🔧 Development

Prerequisites

  • Python 3.10 or higher
  • uv package manager (recommended)

Setup

# Clone the repository
git clone https://github.com/snoodleboot-io/sweet_tea.git
cd sweet_tea

# Install development dependencies
uv sync

# Install pre-commit hooks
uv run pre-commit install

# Run tests
uv run pytest

# Build documentation locally
uv run mkdocs serve

Code Quality

This project uses several tools to maintain code quality:

  • Black: Code formatting
  • isort: Import sorting (compatible with Black)
  • Ruff: Fast linting and additional formatting
  • Bandit: Security scanning
  • MyPy: Type checking

All tools run automatically via pre-commit hooks on git commit.

🤝 Contributing

We welcome contributions! Please see our contributing guide for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests and ensure they pass
  5. Update documentation if needed
  6. Submit a pull request

📄 License

Copyright © 2025 snoodleboot, LLC. Licensed under the Apache License 2.0.

See LICENSE for the full license text.

🙏 Acknowledgments


Sweet Tea Factory System - Production-ready factory patterns for Python applications.

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

sweet_tea-0.1.30.tar.gz (31.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sweet_tea-0.1.30-py3-none-any.whl (20.7 kB view details)

Uploaded Python 3

File details

Details for the file sweet_tea-0.1.30.tar.gz.

File metadata

  • Download URL: sweet_tea-0.1.30.tar.gz
  • Upload date:
  • Size: 31.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for sweet_tea-0.1.30.tar.gz
Algorithm Hash digest
SHA256 e2f3be4ac730d353e1cdf49425d4a379832c17978c529ab318c55da2f62f69f4
MD5 b436037ac0a3915d27def1d838ebe482
BLAKE2b-256 ead300bcfb6317eab8d79b7a0a2222bed03b1bf34c9302ba5f11a8742a6a67cf

See more details on using hashes here.

File details

Details for the file sweet_tea-0.1.30-py3-none-any.whl.

File metadata

  • Download URL: sweet_tea-0.1.30-py3-none-any.whl
  • Upload date:
  • Size: 20.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for sweet_tea-0.1.30-py3-none-any.whl
Algorithm Hash digest
SHA256 2bcdb635d015004614df8cf29bd8a32fbc2cd47a7e83dac4d6b3da0877709976
MD5 0440e2ba9912ebd7a15f4b34cb282de3
BLAKE2b-256 62dad922dda0913068e401395d5ecb5daef13b65a608c11e66f976bdab163e90

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