Skip to main content

philiprehberger-singleton

PyPI Python License: MIT

Thread-safe singleton and multiton pattern decorators.

Requirements

  • Python >= 3.10

Installation

pip install philiprehberger-singleton

Usage

Singleton

The @singleton decorator ensures only one instance of a class exists:

from philiprehberger_singleton import singleton

@singleton
class Database:
    def __init__(self, url: str) -> None:
        self.url = url

db1 = Database("postgres://localhost/mydb")
db2 = Database("postgres://localhost/other")

assert db1 is db2  # same instance
assert db1.url == "postgres://localhost/mydb"

Reset

Use reset() to discard the cached instance (useful in tests):

Database.reset()
db3 = Database("postgres://localhost/new")
assert db3.url == "postgres://localhost/new"

Multiton

The @multiton(key=...) decorator maintains one instance per unique key value:

from philiprehberger_singleton import multiton

@multiton(key="name")
class Connection:
    def __init__(self, name: str, timeout: int = 30) -> None:
        self.name = name
        self.timeout = timeout

cache = Connection("cache", timeout=10)
db = Connection("db", timeout=60)
cache2 = Connection("cache")

assert cache is cache2       # same key -> same instance
assert cache is not db        # different key -> different instance

Reset

Use reset() to discard all cached instances:

Connection.reset()

API

Name Type Description
singleton decorator Makes a class a thread-safe singleton. Returns the same instance on every call.
multiton(key) decorator factory Makes a class a thread-safe multiton. One instance per unique value of the named parameter.
cls.reset() class method Discards cached instance(s), added by both decorators.

Development

pip install -e .
pytest

License

MIT

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.

philiprehberger_singleton-0.1.0-py3-none-any.whl (4.3 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_singleton-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_singleton-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e9ca94836d8bff78ce45ab1b0a8375cb9d212bd3c10e3a697b6af00d82a71872
MD5 78c94f556a370297b406fc4cc2ef631b
BLAKE2b-256 264d2b2f6dbce54088a3f35c8b9da8e0d19be683075e89b564db06998e778e5d

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