Skip to content

Instantly share code, notes, and snippets.

@johnberroa
Created February 22, 2021 19:53
Show Gist options
  • Save johnberroa/da838db3d106c55554134df2b86ac45e to your computer and use it in GitHub Desktop.
Save johnberroa/da838db3d106c55554134df2b86ac45e to your computer and use it in GitHub Desktop.
A Python singleton
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