Created
February 22, 2021 19:53
-
-
Save johnberroa/da838db3d106c55554134df2b86ac45e to your computer and use it in GitHub Desktop.
A Python singleton
This file contains 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
import logging | |
LOG = logging.getLogger(__name__) | |
class Singleton: | |
"""Abstract class that forces only one instance of the child to be created.""" | |
#: Singleton controller; True if an instance of this class has already been created | |
created = False | |
def __init__(self): | |
if self.created: | |
error = PermissionError(f"Only one '{self.__class__.__name__}' can be created!") | |
LOG.exception(error.args[0], exc_info=error) # args[0] is the message | |
raise error | |
self.__create() | |
@classmethod | |
def __create(cls): | |
"""Set this class to 'created' status.""" | |
cls.created = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment