-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsingleton.py
executable file
·47 lines (33 loc) · 949 Bytes
/
singleton.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#! /usr/bin/python
#
# \Author Hans Kramer
#
# \Date Jan 2016
#
import collections
class Singleton(object):
def __init__(self, klass):
self.klass = klass
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
return self.klass(*args)
hash_key = (self.klass, args)
if hash_key not in self.cache:
self.cache[hash_key] = self.klass(*args)
return self.cache[hash_key]
def singleton(klass):
instances = {}
def getinstance(*args, **kwargs):
if klass not in instances:
instances[klass] = klass(*args, **kwargs)
return instances[klass]
return getinstance
if __name__ == "__main__":
import unittest
class TestSingleton(unittest.TestCase):
def __init__(self, *args):
pass
# test it yourself!
# okay okay, after the sprint
unittest.main()