All Projects â†’ Kemaweyan â†’ singleton_decorator

Kemaweyan / singleton_decorator

Licence: other
A testable singleton decorator

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to singleton decorator

oh-my-design-patterns
🎨 Record the articles and code I wrote while learning design patterns
Stars: ✭ 33 (-15.38%)
Mutual labels:  singleton, decorator
data examples
An example app showing different ways to pass to and share data with widgets and pages.
Stars: ✭ 56 (+43.59%)
Mutual labels:  singleton
Kotlin-Singleton-Example
Example of creating Singletons with Kotlin with some MVVM architecture
Stars: ✭ 47 (+20.51%)
Mutual labels:  singleton
Block-Breaker-Original
Arkanoid clone build as part of the Complete Unity C# Developer 2D course (http://gdev.tv/cudgithub)
Stars: ✭ 45 (+15.38%)
Mutual labels:  singleton
tsdi
Dependency Injection container (IoC) for TypeScript
Stars: ✭ 50 (+28.21%)
Mutual labels:  singleton
CLLocationManager-Singleton-Swift
No description or website provided.
Stars: ✭ 13 (-66.67%)
Mutual labels:  singleton
react-design-patterns
An attempt to implement software design patterns in React
Stars: ✭ 315 (+707.69%)
Mutual labels:  singleton
hb-config
hb-config: easy to configure your python project especially Deep Learning experiments
Stars: ✭ 21 (-46.15%)
Mutual labels:  singleton
session-resume
Annotate fields to be persisted on navigation away from the current page
Stars: ✭ 105 (+169.23%)
Mutual labels:  decorator
NYTimes-iOS
🗽 NY Times is an Minimal News 🗞 iOS app 📱 built to describe the use of SwiftSoup and CoreData with SwiftUI🔥
Stars: ✭ 152 (+289.74%)
Mutual labels:  singleton
TezActionSheet
Custom singleton actionSheet with block completion.
Stars: ✭ 18 (-53.85%)
Mutual labels:  singleton
patterns
Good practices to create code in Java, open to other languages. âš¡
Stars: ✭ 14 (-64.1%)
Mutual labels:  singleton
hookleton
globalize your React Hooks without fear using the Hookleton Pattern
Stars: ✭ 39 (+0%)
Mutual labels:  singleton
TezAlertView
Custom singleton alertView with block completion.
Stars: ✭ 17 (-56.41%)
Mutual labels:  singleton
DI-compiler
A Custom Transformer for Typescript that enables compile-time Dependency Injection
Stars: ✭ 62 (+58.97%)
Mutual labels:  singleton
cache-all
Fast, efficient cache engines for both express routes & native nodeJs (redis, in-memory & file cache)
Stars: ✭ 22 (-43.59%)
Mutual labels:  singleton
incache
Powerful key/value in-memory storage or on disk to persist data
Stars: ✭ 16 (-58.97%)
Mutual labels:  singleton
presenter
Easy class decoration.
Stars: ✭ 13 (-66.67%)
Mutual labels:  decorator
design-pattern
🌴 Detail design pattern and give many demos in Java.
Stars: ✭ 28 (-28.21%)
Mutual labels:  singleton
combobox-nav
Attach combobox navigation behavior to <input> or <textarea>.
Stars: ✭ 76 (+94.87%)
Mutual labels:  decorator

singleton-decorator

https://travis-ci.org/Kemaweyan/singleton-decorator.svg?branch=master https://coveralls.io/repos/github/Kemaweyan/singleton-decorator/badge.svg?branch=master

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:

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 wrapped with the decorator. So you cannot call methods using a class name in unit tests:

@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:

$ pip install singleton-decorator

Usage

At first import the singleton decorator:

from singleton_decorator import singleton

Then decorate you classes with this decorator:

@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:

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:

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:

# your_module.py
@singleton
class YourClass:
    def your_method(self):
        ...
# 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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].