singleton-decorator
===================
A testable singleton decorator allows easily create a singleton objects
just adding a decorator to class definition but also allows easily write
unit tests for those classes.
A problem
=========
If you use a simple singleton pattern based on a decorator function that
wraps a class with inner wrapper function like this:
.. code-block::
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
it works fine with your classes, but it makes impossible a direct access
to the class object without decorator. So you cannot call methods using
a class name in unit tests:
.. code-block::
@singleton
class YourClass:
def method(self):
...
YourClass.method(...)
this code would not work because ``YouClass`` actually contains a wrapper function
but not your class object. Also this approach causes another problem if your
tests require separate instances of the objects, so a singleton pattern could
break an isolation of different tests.
Solution
========
The **singleton-decorator** offers a simple solution to avoid both of these
problems. It uses a separate wrapper object for each decorated class and holds
a class within ``__wrapped__`` attribute so you can access the decorated class
directly in your unit tests.
Installation
============
To install the **singleton-decorator** just type in the command line:
.. code-block::
$ pip install singleton-decorator
Usage
=====
At first import the singleton decorator:
.. code-block::
from singleton_decorator import singleton
Then decorate you classes with this decorator:
.. code-block::
@singleton
class YourClass:
...
That's all. Now you could create or get existing instance of your class by
calling it as a simple class object:
.. code-block::
obj = YourClass() # creates a new instance
obj2 = YourClass() # returns the same instance
obj3 = YourClass() # returns the same instance
...
You also could pass args and kwargs into constructor of your class:
.. code-block::
obj = YourClass(1, "foo", bar="baz")
.. NOTE::
Since the singleton pattern allows to create only one instance from
the class, an ``__init__`` method would be called once with args and
kwargs passed at the first call. Arguments of all future calls would
be completely ignored and would not impact the existing instance at all.
Unit testing
============
In your unit tests to run the methods of decorated classes in isolation
without instantiation the object (to avoid running a constructor code),
use the ``__wrapped__`` attribute of the wrapper object:
.. code-block::
# your_module.py
@singleton
class YourClass:
def your_method(self):
...
.. code-block::
# tests.py
class TestYourClass(TestCase):
def test_your_method(self):
obj = mock.MagicMock()
YourClass.__wrapped__.your_method(obj)
...
This test runs a code of the ``your_method`` only using a mock object
as the ``self`` argument, so the test would be run in complete isolation
and would not depend on another pieces of your code including a constructor
method.
Raw data
{
"_id": null,
"home_page": "https://github.com/Kemaweyan/singleton_decorator",
"name": "singleton-decorator",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "singleton decorator unittest",
"author": "Taras Gaidukov",
"author_email": "kemaweyan@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/33/98/a8b5c919bee1152a9a1afd82014431f8db5882699754de50d1b3aba4d136/singleton-decorator-1.0.0.tar.gz",
"platform": "",
"description": "singleton-decorator\n===================\n\nA testable singleton decorator allows easily create a singleton objects\njust adding a decorator to class definition but also allows easily write\nunit tests for those classes.\n\nA problem\n=========\n\nIf you use a simple singleton pattern based on a decorator function that\nwraps a class with inner wrapper function like this:\n\n.. code-block::\n\n def singleton(cls):\n instances = {}\n def wrapper(*args, **kwargs):\n if cls not in instances:\n instances[cls] = cls(*args, **kwargs)\n return instances[cls]\n return wrapper\n\nit works fine with your classes, but it makes impossible a direct access\nto the class object without decorator. So you cannot call methods using\na class name in unit tests:\n\n.. code-block::\n\n @singleton\n class YourClass:\n def method(self):\n ...\n YourClass.method(...)\n\nthis code would not work because ``YouClass`` actually contains a wrapper function\nbut not your class object. Also this approach causes another problem if your\ntests require separate instances of the objects, so a singleton pattern could\nbreak an isolation of different tests.\n\nSolution\n========\n\nThe **singleton-decorator** offers a simple solution to avoid both of these\nproblems. It uses a separate wrapper object for each decorated class and holds\na class within ``__wrapped__`` attribute so you can access the decorated class\ndirectly in your unit tests.\n\nInstallation\n============\n\nTo install the **singleton-decorator** just type in the command line:\n\n.. code-block::\n\n $ pip install singleton-decorator\n\nUsage\n=====\n\nAt first import the singleton decorator:\n\n.. code-block::\n\n from singleton_decorator import singleton\n\nThen decorate you classes with this decorator:\n\n.. code-block::\n\n @singleton\n class YourClass:\n ...\n\nThat's all. Now you could create or get existing instance of your class by\ncalling it as a simple class object:\n\n.. code-block::\n\n obj = YourClass() # creates a new instance\n obj2 = YourClass() # returns the same instance\n obj3 = YourClass() # returns the same instance\n ...\n\nYou also could pass args and kwargs into constructor of your class:\n\n.. code-block::\n\n obj = YourClass(1, \"foo\", bar=\"baz\")\n\n.. NOTE::\n\n Since the singleton pattern allows to create only one instance from\n the class, an ``__init__`` method would be called once with args and\n kwargs passed at the first call. Arguments of all future calls would\n be completely ignored and would not impact the existing instance at all.\n\nUnit testing\n============\n\nIn your unit tests to run the methods of decorated classes in isolation\nwithout instantiation the object (to avoid running a constructor code),\nuse the ``__wrapped__`` attribute of the wrapper object:\n\n.. code-block::\n\n # your_module.py\n @singleton\n class YourClass:\n def your_method(self):\n ...\n\n.. code-block::\n\n # tests.py\n class TestYourClass(TestCase):\n def test_your_method(self):\n obj = mock.MagicMock()\n YourClass.__wrapped__.your_method(obj)\n ...\n\nThis test runs a code of the ``your_method`` only using a mock object\nas the ``self`` argument, so the test would be run in complete isolation\nand would not depend on another pieces of your code including a constructor\nmethod.\n",
"bugtrack_url": null,
"license": "GPLv3",
"summary": "A testable singleton decorator",
"version": "1.0.0",
"split_keywords": [
"singleton",
"decorator",
"unittest"
],
"urls": [
{
"comment_text": "",
"digests": {
"md5": "9b0011c7d33a671bc02b58362ef3dc18",
"sha256": "1a90ad8a8a738be591c9c167fdd677c5d4a43d1bc6b1c128227be1c5e03bee07"
},
"downloads": -1,
"filename": "singleton-decorator-1.0.0.tar.gz",
"has_sig": false,
"md5_digest": "9b0011c7d33a671bc02b58362ef3dc18",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 2791,
"upload_time": "2017-08-10T19:52:45",
"upload_time_iso_8601": "2017-08-10T19:52:45.903156Z",
"url": "https://files.pythonhosted.org/packages/33/98/a8b5c919bee1152a9a1afd82014431f8db5882699754de50d1b3aba4d136/singleton-decorator-1.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2017-08-10 19:52:45",
"github": true,
"gitlab": false,
"bitbucket": false,
"github_user": "Kemaweyan",
"github_project": "singleton_decorator",
"travis_ci": true,
"coveralls": true,
"github_actions": false,
"lcname": "singleton-decorator"
}