Skip to content

Instantly share code, notes, and snippets.

@c7h
Created June 14, 2015 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c7h/91528dd8069d33d7ea25 to your computer and use it in GitHub Desktop.
Save c7h/91528dd8069d33d7ea25 to your computer and use it in GitHub Desktop.
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
Copy link
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