Skip to content

randydu/py-singleton

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Singleton pattern for python 2 & 3

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages