Although people may, or may not, consider Python a true object oriented programming language, it supports the class-based OOP reasonably well, comparable to those found in more hard-core OOP languages such as C++, Java, and C#.
In general, for cases where the singleton pattern may be needed, a better option is to use modules as a unit. (Similar to what we do in Go.)
If OOP features are needed,
a singleton in Python
can be implemented using metaclass
.
Singleton Design Pattern in Python
singleton.py
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(
Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
main.py
from singleton import Singleton
class MySingleton(metaclass=Singleton):
name = "Nobody"
def hello(self):
print(f"Hello, {self.name}!")
if __name__ == '__main__':
MySingleton().hello()
s = MySingleton()
s.name = "Joe"
s.hello()
MySingleton().hello()