0

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

Nick
  • 2,924
  • 4
  • 36
  • 43
  • 2
    Just some notes: 1) it's not a "singleton" if there's no single instance. Your code is just using `Test` as a pseudo-namespace. There's really zero difference between using modules as namespaces and classes as namespaces, so this is just global variables with extra steps. 2) you _can_ create instances of `Test` - just try `Test()` – Brian61354270 Aug 12 '23 at 13:22
  • **Test** is not an abstract Class it is a sub-class of an abstract base Class. It can be instanced. – user19077881 Aug 12 '23 at 13:35
  • @Brian61354270 Thanks - I forgot to add an abstractmethod. The question, however, still stays. – Nick Aug 12 '23 at 14:41
  • Check out [Creating a singleton in Python](https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python) – JonSG Aug 12 '23 at 15:03
  • 1
    @JonSG Thanks - I am aware of this post. In fact, it is one of the reasons for my post - as I see the class attribute of an abstract class as a much easier implementation of the singleton pattern compared to most of the ones suggested in that post. – Nick Aug 12 '23 at 15:08
  • Ya, I added it for future viewers who found this post and might be interested in potential singleton implementations :-) – JonSG Aug 12 '23 at 15:20

0 Answers0