Skip to main content

py-singleton

Singleton pattern for python 2 & 3.

Install

pip install py-singleton

Test

in the root folder, run pytest:

pytest

Dependencies

None

unit test needs pytest.

API

  • Apply class decorator singleton to any class;

  • Expected behaviors:

    • class can be instantiated as usual, but only one instance is created;
    • apis to access the class instance:
      @singleton
      class Server(object):
        pass
    
      srv = Server()
    

    or

      srv = Server.instance()
    
    • the function _init_() of decorated class will be called once and only once when the instance is created.

Example

from py_singleton import singleton

    @singleton
    class A(object):
        count = 0
        def __init__(self):
            A.count += 1

    a1 = A()
    a2 = A()
    a3 = A.instance()

    assert A.count == 1
    assert a1 is a2
    assert a1 is a3

Limitation

For best performance, the code to create instance is not thread-safe, however, after the instance is created it should be safe for multi-threading.

It is recommended to call instance() once during the initial phrase of your app in a single thread.

Release files for py-singleton 1.0.0

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

Source distribution (sdist)

Source distribution for py-singleton 1.0.0
File Size Uploaded
py-singleton-1.0.0.tar.gz 2.9 kB Details

Release files / py-singleton-1.0.0.tar.gz

Download URL py-singleton-1.0.0.tar.gz
Size 2.9 kB
Tags Source
SHA-256 checksum
How to use checksums
9922a69f6e6b9390e5c1b3d2b39e119d5fcffa92d9c3145de3b8533a93077fb7
BLAKE2b-256 checksum
How to use checksums
e94925659b2596ab0e536c168a90358e9cb4a70fd776955a6174a7fde76a9264
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.2

Release history Release notifications | RSS feed

This release

1.0.0 This release

1 release file

0.9.3

1 release file

0.9.2

1 release file

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