1

Background: I am writing a module in order to set-up an embedded system. In this context I need to load some modules and perform some system settings.

Context: I have a parent class holding some general code (load the config file, build ssh connection etc.) used for several child classes. One of them is the module class that sets up the module and therefore uses among otherthings the ssh connection and the configuration file. My goal is to share the configuration file and the connection with the next module, that will be setup. For the connection its just a waste to build and destroy it all the time, but for the configuration file, changes during setup can lead to undefined behavior.

Research/ approaches:

  • I tried using class variables, however they aren't passed when initaiting a new module object.

  • Futher, I tried using global variables, but since the parent class and the child classes are in different files, This won't work (Yes, i can put them all in one file but this will be a mess) Also using a getter function from the file where I defined the global variable didn't work.

  • I am aware of the 'builtin' solution from How to make a cross-module variable? variable, but feel this would be a bit of an overkill...

  • Finally, I can keep the config file and and the connection in a central script and pass them to each of the instances, but this will lead to loads of dependencies and I don't think it's a good solution.

So here is a bit of code with an example method, to get some file paths. The code is set up according to approach 1 (class vaiables)

An example config file:

Files:
  Core:
    Backend:
      - 'file_1'
      - 'file_2'
Local:
  File_path:
    Backend: '/the/path/to'

The Parent class in setup_class.py

import os
import abc
import yaml

class setup(object):
    __metaclass__ = abc.ABCMeta
    configuration = []

    def check_for_configuration(self, config_file):
        if not self.configuration:
            with open(config_file, "r") as config:
                self.configuration = yaml.safe_load(config)

    def get_configuration(self):
        return self.configuration

    def _make_file_list(self, path, names):
        full_file_path = []
        for file_name in names:
            temp_path = path + '/' + file_name
            temp_path = temp_path.split('/')
            full_file_path.append(os.path.join(*temp_path))
        return full_file_path

    @abc.abstractmethod
    def install(self):
        raise NotImplementedError

The module class in module_class.py

from setup_class import setup

class module(setup):
    def __init__(self, module_name, config_file = ''):
        self.name = module_name
        self.check_for_configuration(config_file)

    def install(self):
        self._backend()

    def _backend(self):
        files = self._make_file_list(
                    self.configuration['Local']['File_path']['Backend'],
                    self.configuration['Files'][self.name]['Backend'])
        if files:
            print files

And finally a test script:

from module_class import module
Analysis = module('Analysis',"./example.yml")
Core = module('Core', "./example.yml")
Core.install()

Now, when running the code, the config file is loaded everytime, a new module object is initaiated. I would like to avoid this. Are there approaches I have not considdered? What's the neatest way to achive this?

Lucas
  • 395
  • 1
  • 11

1 Answers1

1

Save your global values in a global dict, and refer to that inside your module.

cache = {}

class Cache(object):
    def __init__(self):
        global cache
        self.cache = cache
eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20
  • Thanks alot! I don't really understand how the dict is different from the variables I tried before, but anyways, it works perfectly! – Lucas Apr 01 '19 at 14:58
  • Because a dict in python is a mutable variable, and maybe the others you were using were not. Mutable variables are only analyzed once at startup and then any changes reflect globally. This works great when you need a constant source of truth through your whole application without checking a config file or database – eatmeimadanish Apr 01 '19 at 19:42