This might be a silly question since I just learnt about Metaclasses....
If you have 2 Singleton classes each in their own file, is it poor practice to duplicate the Singleton metaclass definition in both files, like
Apple.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]
class Apple(metaclass=Singleton):
pass
print(Apple() == Apple()) # True
Orange.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]
class Orange(metaclass=Singleton):
pass
print(Orange() == Orange()) # True
Or should we move the Singleton metaclass code into its own file Singleton.py, and import them into Apple.py and Orange.py?
Or use a @singleton decorator from the package singleton-decorator?
is it poor practice to duplicate the Singleton metaclass definition in both files, likeYes. Repeating yourself is never a good thing.abcmodule in the standard library does. Metaclasses are magical in some ways, but not in this.Singletonclass be a subclass ofABCMetainstead oftype? I am not familiar with theabcmodule, will appreciate an explanationSingletonin its own module? Don't copy and paste code. That's just Wrong.