Skip to content

Instantly share code, notes, and snippets.

@vladiibine
Created November 9, 2020 15:58
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 vladiibine/d9ccd767fea6167cd7e8e078936c33a7 to your computer and use it in GitHub Desktop.
Save vladiibine/d9ccd767fea6167cd7e8e078936c33a7 to your computer and use it in GitHub Desktop.
# It will be slightly harder to create multiple instances of this class
class S:
def __init__(self, arg1, arg2):
# Dummy method. Used for reflection only
pass
@classmethod
def get_instance(cls, arg1, arg2):
# Dummy method. Used for reflection only
pass
@staticmethod
def initialize():
magic_value = object()
instances = [None]
def __init__(self, arg1, arg2, secret_arg=None):
if secret_arg is not magic_value:
raise Exception("Told you this is a singleton")
self.arg1 = arg1
self.arg2 = arg2
@classmethod
def get_instance(cls, arg1, arg2):
print("That's the way to do it!")
if instances[0]:
instances[0] = cls(arg1, arg2, magic_value)
return instances[0]
return {'__init__': __init__, 'get_instance': get_instance}
locals().update(initialize.__func__())
del initialize
if __name__ == '__main__':
s1 = S.get_instance(1,2)
s2 = S.get_instance(3,4)
print(s2 is s1)
S(2,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment