Python Singleton Class with Configurations

Senior Brogrammer
2 min readJun 8, 2022

This is a concept I came across recently and attempted to integrate into one of my projects with configurations. The issues I’ve ran into configuration files to this day, is there is a million ways to handle them and I just created another.

Configuration | Credit: Pete Linforth on Pixabay

Introduction

I have a configuration file that is difficult to keep from being a global variable to see or opening several times per module. The alternative could be to keep a file of Python constants that switch based on environment.

So the configuration file could potentially look like this:

# config.py
MY_CONFIG_1 = "my-sick-config-1"
MY_CONFIG-2 = "my-sick-config-2"
...

The only tricky part of this setup is handling credentials which may require an API call (or copying a version of the file locally into the environment one).

My Idea

So I came across a reading about Python singletons and decided what is the harm in using this to a configuration file. I’d have a single instance of the class that would be generated and could re-use it each time, where I would only open the file once.

I started at a couple articles and Stack Overflow answers, but ended up at the Python documentation that had an example showcase of a singleton implementation. I ended up using this for starters and worked my way through the simple setup.

Note: The example I do below is a significantly simpler setup than what I have, however it should demonstrate what I am trying to do.

So using the Python implementation of singleton I came up with the following idea:

# singleton.py
class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
# config.py
class Config(Singleton):
def init(self):
self.configurations = self._read('config.yaml')

def _read(self, filename):
with open(filename) as stream:
return yaml.safe_load(stream)
conf1 = Config()
conf2 = Config()
assert conf1 == conf2
Senior Brogrammer