Skip to content

Instantly share code, notes, and snippets.

@ccarouge
Created February 15, 2024 05:01
Show Gist options
  • Save ccarouge/3364fb61615fe07c58d584e4a0adb0d7 to your computer and use it in GitHub Desktop.
Save ccarouge/3364fb61615fe07c58d584e4a0adb0d7 to your computer and use it in GitHub Desktop.
Create singleton object in python
"""Singleton Object."""
class Singleton(type):
"""Singleton base (meta) class."""
_instances = {}
def __call__(cls, *args, **kwargs):
"""Create the object on first call, return otherwise.
Returns
-------
object
The object that metaclasses this base class.
"""
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment