From c1668ded37cbbe54be5a63a87954932d7bf74db8 Mon Sep 17 00:00:00 2001 From: Ivan Malison Date: Thu, 20 Aug 2015 02:11:55 -0700 Subject: [PATCH] singleton with metaclass --- dotfiles/lib/python/singleton.py | 24 ++++++++++++++++++++++++ dotfiles/lib/python/singleton_test.py | 15 +++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 dotfiles/lib/python/singleton.py create mode 100644 dotfiles/lib/python/singleton_test.py diff --git a/dotfiles/lib/python/singleton.py b/dotfiles/lib/python/singleton.py new file mode 100644 index 00000000..6d9e28e8 --- /dev/null +++ b/dotfiles/lib/python/singleton.py @@ -0,0 +1,24 @@ +def singleton(klass): + original_init = klass.__dict__.get('__init__') + class klassMeta(type, klass): + + def __init__(self, *args): + original_init(self) + super(klass, self).__init__(*args) + + class Temp(object): + __metaclass__ = klassMeta + Temp.__name__ = klass.__name__ + klassMeta.__name__ = "{}Meta".format(klass.__name__) + return Temp + + +@singleton +class TestSingleton(object): + + def __init__(self): + self.a = 22 + self.b = 44 + + def hey(self): + return self.a + self.b diff --git a/dotfiles/lib/python/singleton_test.py b/dotfiles/lib/python/singleton_test.py new file mode 100644 index 00000000..404ecf37 --- /dev/null +++ b/dotfiles/lib/python/singleton_test.py @@ -0,0 +1,15 @@ +from . import singleton + + +def test_singleton(): + @singleton.singleton + class TestSingleton(object): + + def __init__(self): + self.a = 22 + self.b = 44 + + def hey(self): + return self.a + self.b + assert TestSingleton.a == 22 + assert TestSingleton.hey() == 66