Last active
July 31, 2020 04:04
-
-
Save guionardo/08d24f4a454b8548f586e22cb0bf4c29 to your computer and use it in GitHub Desktop.
Python singleton decorator class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Singleton | |
class DBConnection(object): | |
def __init__(self): | |
"""Initialize your database connection here.""" | |
pass | |
def __str__(self): | |
return 'Database connection object' | |
# Let’s access this connection class: | |
c1 = DBConnection.Instance() | |
c2 = DBConnection.Instance() | |
print("Id of c1 : {}".format(str(id(c1)))) | |
print("Id of c2 : {}".format(str(id(c1)))) | |
print("c1 is c2 ? " + str(c1 is c2)) | |
# Output: | |
# Id of c1 : 139699882512960 | |
# Id of c2 : 139699882512960 | |
# c1 is c2 ? True | |
# If we do as below, we will get TypeError: | |
try: | |
p = DBConnection() | |
except TypeError as ex: | |
print("ERROR: {}".format(ex.message)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Singleton: | |
def __init__(self, cls): | |
self._cls = cls | |
def Instance(self, *args, **kwargs): | |
try: | |
return self._instance | |
except AttributeError: | |
self._instance = self._cls(*args, **kwargs) | |
return self._instance | |
def __call__(self): | |
raise TypeError('Singletons must be accessed through `Instance()`.') | |
def __instancecheck__(self, inst): | |
return isinstance(inst, self._cls) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment