psygo
psygo

Reputation: 7633

How to import externally into a module

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?

Upvotes: 1

Views: 59

Answers (1)

fberg
fberg

Reputation: 21

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

Check out What is __init__.py for?

Upvotes: 1

Related Questions