Skip to main content

A type-friendly, thread-safe singleton base class for Python 3.10+. Very simple to use and test-friendly.

Project description

singleton-base

A type-friendly, thread-safe singleton base class for Python 3.12+. Very simple to use and test-friendly.

Installation

Using pip

pip install singleton-base

Using Uv

uv add singleton-base

Using Poetry

poetry add singleton-base

Features

  • Thread-safe: Multiple threads can safely create instances
  • Type-friendly: Full type hint support, including Self returns and PEP 695 generic syntax
  • Test-friendly: Easy instance management for testing scenarios
  • Zero runtime dependencies

Usage

Usage Example

Subclass using SingletonBase to make your class a singleton. All returned instances will now be the same object.

from singleton_base import SingletonBase


class MySingleton(SingletonBase):
    """A singleton class example that holds an integer value."""

    def __init__(self, value: int) -> None:
        self.value = value


class AnotherSingleton(SingletonBase):
    """Another singleton class example that holds a string value."""

    def __init__(self, value: str) -> None:
        self.value = value


# Initially, no instance exists
print(MySingleton.has_instance())  # False

# Two equivalent ways to create the singleton:
instance = MySingleton(42)
# or
instance = MySingleton.get_instance(value=42)

print(MySingleton.has_instance())  # True
print(instance.value)              # 42

# Subsequent calls return the same instance.
# Note: any args passed after the first construction are ignored.
instance2 = MySingleton.get_instance(value=99)
print(instance is instance2)       # True
print(instance2.value)             # 42

# Other singleton classes are independent — each maintains its own instance:
another = AnotherSingleton(value="Hello")
print(instance is another)         # False

# Reset to allow re-initialization (handy for tests):
MySingleton.reset_instance()
print(MySingleton.has_instance())  # False

# After a reset, the next call constructs a fresh instance:
instance3 = MySingleton.get_instance(value=9001)
print(instance3.value)             # 9001

Available Methods

Method Description
get_instance(*args, **kwargs) Returns the singleton instance, constructing it with *args, **kwargs if it does not yet exist.
has_instance() Returns True if the singleton instance has been created.
reset_instance() Destroys the current instance, allowing re-initialization.

Wrapper API: SingletonWrap

When subclassing isn't an option (third-party classes, dataclasses, etc.), use SingletonWrap to wrap an existing class instead:

from singleton_base import SingletonWrap


class Service:
    def __init__(self, host: str, port: int) -> None:
        self.host = host
        self.port = port


service_singleton = SingletonWrap(Service, "localhost", 8080)

service = service_singleton.get()      # constructs on first access
same_service = service_singleton.get() # returns the same instance
print(service is same_service)         # True

service_singleton.reset_instance()
print(service_singleton.has_instance())  # False

SingletonWrap exposes the same has_instance() / reset_instance() lifecycle as SingletonBase, plus get() / get_instance() (aliases) for retrieval.

Python Version Compatibility

Supports Python 3.12–3.14 with full test coverage across every version. No version-conditional code, no runtime dependencies.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

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

singleton_base-1.2.6-py3-none-any.whl (13.5 kB view details)

Uploaded Python 3

File details

Details for the file singleton_base-1.2.6-py3-none-any.whl.

File metadata

  • Download URL: singleton_base-1.2.6-py3-none-any.whl
  • Upload date:
  • Size: 13.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for singleton_base-1.2.6-py3-none-any.whl
Algorithm Hash digest
SHA256 107a3e607db06b5e70abd94c27fd3f57079bf9b492ca4048f6cf11c164431756
MD5 e3b8885259e491ea7222353ced87a6c4
BLAKE2b-256 9b8955fa3bd3c3cc935878c8b7bab06b3a102052b9b94a3f97390a878b404ed8

See more details on using hashes here.

Provenance

The following attestation bundles were made for singleton_base-1.2.6-py3-none-any.whl:

Publisher: build-wheels.yml on sicksubroutine/singleton-base

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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