You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance method. Here's an example:
@SingletonclassFoo:
def__init__(self):
print'Foo created'f=Foo() # Error, this isn't how you get the instance of a singletonf=Foo.Instance() # Good. Being explicit is in line with the Python Zeng=Foo.Instance() # Returns already created instanceprintfisg# True
And here's the code:
classSingleton:
""" A non-thread-safe helper class to ease implementing singletons. This should be used as a decorator -- not a metaclass -- to the class that should be a singleton. The decorated class can define one `__init__` function that takes only the `self` argument. Also, the decorated class cannot be inherited from. Other than that, there are no restrictions that apply to the decorated class. To get the singleton instance, use the `Instance` method. Trying to use `__call__` will result in a `TypeError` being raised. """def__init__(self, decorated):
self._decorated=decorateddefInstance(self):
""" Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """try:
returnself._instanceexceptAttributeError:
self._instance=self._decorated()
returnself._instancedef__call__(self):
raiseTypeError('Singletons must be accessed through `Instance()`.')
def__instancecheck__(self, inst):
returnisinstance(inst, self._decorated)
The text was updated successfully, but these errors were encountered:
For python in general it is suggested that there be a single module to handle singleton operations. However, I nixed this because of the way that utils operates.
So the singleton class above in the example is what we're implementing in the Utils class to check if its an instance, correct? Sorry, I just need a bit of clarification
Yeah, so the way a singleton works is that it creates a single object when it's first referenced, and all subsequent module that reference it, reference that object.
Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance method. Here's an example:
And here's the code:
The text was updated successfully, but these errors were encountered: