1

1. What I would like to do

Currently, I have a module that calls many others inside it, and, inside them there are other imports being repeated in each and every one of them, as they oftentimes need the same methods in order to work. So, instead of repeating the imports, I would like to say something like for these modules, execute these imports.

2. What I've come up with so far

The only way I know how to do this so far is to create a .json dictionary with the appropriate structure to import the respective modules. However, this only minimizes the problem, since there should be with open(...) statements inside each module anyway.

3. My "Solution" Code

{
 "import module_x" : [
                      "module1.py",
                      "module2.py"
                     ]
}

And then, inside module1 and module2, I would:

import json

with open(path_to_imports + 'imports.json', 'r') as f:
    import_dict = json.load(f)

for key, mods in import_dict.items():
    if __file__ in mods:
        exec(key)

Now, is there a better, more pythonic, way of doing this?

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76

1 Answers1

1

You could use the Python __init__.py file to handle this.

Check out What is __init__.py for?

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
fberg
  • 21
  • 4
  • The `__init__.py` file indeed helps a lot indeed. But I'm still can't make selective imports based on the file/module that is calling the importing. I don't quite know how to get the name of the file that is calling the `__init__.py` imports (I've tried it with the *stack* from the `inspect` library already), which makes me unable to selectively import stuff. I can however simplify things already, but everytime I run a module, it will be importing everything that's relevant to the package but not only to the specific module. – Philippe Fanaro May 24 '19 at 15:03
  • Maybe I can make this selective export using the `__all__` variable? Is it possible to create dictionary inside it and use the key/values to selectively export stuff? – Philippe Fanaro May 29 '19 at 20:27