I am writing an object-oriented app to help our developers manage some cloud systems. I’d like to make the configuration information available to all the classes, but I’m not sure of a good way to do that. Everything I can think of seems to fall under the category of “global variables” which as far as I know is a Very Bad Thing.

I already have a logging Mixin class that enables logging for every class that inherits it, and I was wondering if that’s the right way to approach the configuration data:

class LoggingMixin:
    @classmethod
    @property
    def log(cls):
        return logging.getLogger(cls.__name__)

class TestClassA(LoggingMixin):
    def testmethod1(self):
        self.log.debug("debug message from test class A")

if __name__ == "__main__":
    logging.basicConfig(
        format="{created:<f} {levelname:>5s} {name}.{funcName:>8s} |{message}|",
        level=logging.DEBUG,
        style="{",
    )

    a = TestClassA()
    a.testmethod1()

Outputs (in case you are curious)

1688494741.449282 DEBUG TestClassA.testmethod1 |debug message from test class A|

What’s a good way of making data from a class available to all classes/objects? It wouldn’t be static, it’d be combined from a JSON file and any command line parameters.

If I copied the example above but changed it to a ConfigMixin, would that work? With the logging example, each class creates its own logger object when it first calls self.log.debug, so that might not work because each object needs to get the same config data.

Is there a pattern or other design that could help? How do you make configuration data available to your whole app? Do you have a config object that can get/set values and saves to disk, etc?

Thank you for reading, my apologies for poorly worded questions.

  • const void*
    link
    fedilink
    English
    11 year ago

    You have the right idea.

    One approach is to store cfg in json w/a class that reads that json. Remember to validate the json vs schema first!

    That cfg class should also set env vars so that you don’t need to rely on env vars being correctly set by an invoking shell (json to rescue).

    The cfg object instance becomes a parameter to class constructors or module functions.

    If the idea of passing around a cfg instance is appalling, then hello global / singleton pattern!