Skip to content
Snippets Groups Projects
Unverified Commit e5e441e4 authored by Piotr Maślanka's avatar Piotr Maślanka Committed by GitHub
Browse files

Merge pull request #23 from piotrmaslanka/issue-15

fixes #15
parents 2fc62814 047a5233
No related branches found
Tags v2.0.22rc3
No related merge requests found
## v2.0.22rc3
* fixes #15
* fixes #20
* fixes #21
......
......@@ -12,6 +12,8 @@ from .typecheck import typed, Callable, Sequence, \
TypeVar, Mapping, Iterable, Any, Optional, CallSignature, \
Number, coerce, Set, Dict, List, Tuple, checked_coerce, for_argument, \
precondition, PreconditionError
from .structures import TimeBasedHeap, Heap, typednamedtuple, OmniHashableMixin
from .singleton import Singleton
__all__ = [
'typednamedtuple', 'OmniHashableMixin'
......@@ -22,6 +24,7 @@ __all__ = [
'CallSignature', 'Number',
'Set', 'Dict', 'List', 'Tuple', 'checked_coerce', 'for_argument',
'precondition', 'PreconditionError',
'rethrow_as', 'silence_excs'
'rethrow_as', 'silence_excs',
'Singleton'
]
# coding=UTF-8
from __future__ import print_function, absolute_import, division
import functools
import six
__all__ = [
'Singleton',
]
if six.PY3:
# Taken from https://wiki.python.org/moin/PythonDecoratorLibrary
def Singleton(cls):
"""
Make a singleton out of decorated class.
Usage:
@Singleton
class MyClass(object):
...
"""
cls.__new_old__ = cls.__new__
@functools.wraps(cls.__new__)
def singleton_new(cls, *args, **kw):
it = cls.__dict__.get('__it__')
if it is not None:
return it
cls.__it__ = it = cls.__new_old__(cls, *args, **kw)
it.__init_old__(*args, **kw)
return it
cls.__new__ = singleton_new
cls.__init_old__ = cls.__init__
cls.__init__ = object.__init__
return cls
else:
class _SingletonWrapper:
"""
A singleton wrapper class. Its instances would be created
for each decorated class.
"""
def __init__(self, cls):
self.__wrapped__ = cls
self._instance = None
def __call__(self, *args, **kwargs):
"""Returns a single instance of decorated class"""
if self._instance is None:
self._instance = self.__wrapped__(*args, **kwargs)
return self._instance
# taken from https://pypi.python.org/pypi/singleton-decorator/1.0.0
def Singleton(cls):
"""
A singleton decorator. Returns a wrapper objects. A call on that object
returns a single instance object of decorated class. Use the __wrapped__
attribute to access decorated class directly in unit tests.
"""
return _SingletonWrapper(cls)
# coding=UTF-8
from __future__ import print_function, absolute_import, division
import unittest
from satella.coding import Singleton
class TestSingleton(unittest.TestCase):
def test_singleton(self):
@Singleton
class MyClass(object):
def __init__(self):
self.a = 5
a = MyClass()
b = MyClass()
a.a = 6
self.assertEqual(b.a, 6)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment