2

What's the proper way to manage configuration files that are embedded in a python module.

I have a python module (e.g. my_py_logger) that does a certain task (i.e. centralized logging). It's meant to be used by other python applications developed by the team. Once it is imported in a python application (e.g. my_py_app_a), developers are able to call a method in the logging module that init's the logging module. This method reads a config file. That config file is inside the my_py_logger package.

When I call this method from another package, python is not able to find the config file because the root folder has changed from my_py_logger's root source folder to my_py_app_a's root source folder.

my_py_logger __init__.py config/ default.conf init_logger.py

my_py_app_a __init__.py app.py

I tried to use importlib.import_module(__name__) in the my_py_logger module to get the absolute path of the main file in my_py_logger, so I can technically extract the parent directory from that string/path and concatenate "../config/default.conf" but this feels like a poor solution. I'm sure there is a better way to handle this situation. Maybe putting this as a config file is not the right solution, but I'm sure I'm not the first guy to try this in python.

What would be the correct solution?

6
  • 1
    What about creating ~/.my_py_logger/default.conf (if it doesn't exist) at logger init? This would allow a default config file per user.
    – FabienP
    Aug 20, 2018 at 20:31
  • This doesn't meet my requirements as I would need to ship default.conf separately with the module. And if it is missing, I would need to package a default.conf in the module which brings us to the original question, how do you refer a .conf file packaged in a module A when module A is imported in module B? Aug 21, 2018 at 12:06
  • Well, you don't need to ship it separately from your module, just copy it from init_logger.py using something like pathlib.Path(__file__).parent.joinpath('config', 'default.conf'). Anyway, storing and modifying the config file inplace inside you module structure, from external modules, does not seems to be a good idea.
    – FabienP
    Aug 21, 2018 at 19:41
  • How could this be done with storing a conf file? What's the norm for this in the python world? Aug 21, 2018 at 21:47
  • 1
    There is no norm, and a few valid approaches actually (a quick example for instance.) You could also use a ~/.loggerrc file, similar to .bashrc or .condarc approaches.
    – FabienP
    Aug 22, 2018 at 19:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.