Created
February 15, 2024 05:01
-
-
Save ccarouge/3364fb61615fe07c58d584e4a0adb0d7 to your computer and use it in GitHub Desktop.
Create singleton object in python
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
"""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