I have a pandas dataframe which is defined as a variable in a module and is accessed (and modified) by various functions within the module. This is not a good design for various reasons including testability.
I would like to replace this module-level variable with some sort of singleton. There are a number of ways to implement them in Python. A common one is to use metaclass which limits the number of instances created to one. There also many others listed, among others, here.
I wonder why not use a class attribute of an abstract class which cannot be instantiated at all?
I have tested this by defining a counter within an abstract class and incrementing it outside of the base class. It works.
I am concerned that I haven't seen this used. So my question is - why is this not being used as a simple implementation of the singleton pattern?
EDIT 1: I forgot to add an abstractmethod to the class - now it is added. The question of the post still stays.
EDIT 2: One of the reasons why I am asking this is because one (weak) implementation of the singleton pattern is via a class attribute. The idea being that this attribute exists in the namespace of the class and thus is a "singleton". However, class attributes if accessed via an instance, essentially, mutate into instance attributes. This issue is avoided if abstract classes are used as no instances can be created thus the class attribute can exist as a true singleton.
from abc import ABC, abstractmethod
class Test(ABC):
counter = 0
@abstractmethod
def some_method():
pass
Test.counter += 1