Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
the _drop-method is used for unittesting. Easy way to get rid of all your old instances.
__author__ = 'Christoph Gerneth'
class SingletonType(type):
def __call__(self, *args, **kwargs):
try:
return self.__instance
except AttributeError:
self.__instance = super(SingletonType, self).__call__(*args, **kwargs)
return self.__instance
def _drop(self):
"Drop the instance (for testing purposes)."
del self.__instance
@c7h

This comment has been minimized.

Copy link
Owner Author

c7h commented Jun 14, 2015

how to use the singleton instance:

class SingletonObject(object):
    __metaclass__ = SingletonType

and how to use them in unittests:

import unittest
class SingletonTypeTestCase(unittest.TestCase):
    def test_something(self):
        [SingletonObject() for i in range(10)]
    def tearDown(self):
        SingletonObject._drop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.