0

I have a module in my program, which is imported and used in pretty much every other module in my program.

The usage is both in global (file) scope and in local (function) scope.

I want to be able to configure my entire system to work also with a different module, in other words - I want to be able to replace that module "under the hood" in a clean manner.

The two modules share the same API of course.

I have established the following solution for this:

  1. Implement the functionality of both modules in the same module
  2. Add a toggle function within that module, which determines which functionality is in use
  3. Call that function at the very beginning of my program, i.e., at the top of the Python file which I execute from a command-line:
import baseModule
baseModule.toggle(True)

But this feels extremely "unorthodox"; is there a more conventional/pythonic way of doing this?

  • 2
    I would implement each module in its own file/directory and alias when I need it. Like `import moduleA as module` when I need `moduleA` and `import moduleB as module` when I need `moduleB`. – Nathan Furnal Jul 05 '22 at 10:22
  • This sounds like a use case for Dependency Injection. A library I have used for this in the past is https://github.com/ivankorobkov/python-inject See also this answer https://stackoverflow.com/a/31813464/202168 – Anentropic Jul 05 '22 at 10:24
  • @NathanFurnal: I would then need to add that `import` statement in each and every file which uses that common module. I am looking for a way which will allow me to configure this in a single place in the code, preferably in a "top-level" file (i.e., rather than inside that module itself). –  Jul 05 '22 at 10:27
  • @bbbbbbbbb You can fiddle with the `__init__.py` and rename modules in some way. Like [shown here](https://stackoverflow.com/questions/24322927/python-how-to-alias-module-name-rename-with-preserving-backward-compatibility) and [here as well](https://stackoverflow.com/questions/57093638/rename-python-subpackage-mark-old-name-as-deprecated). I've never used it so idk how robust it may be – Nathan Furnal Jul 05 '22 at 10:34

0 Answers0