Reputation: 7633
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.
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.
{
"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
Reputation: 21
You could use the Python __init__.py
file to handle this.
Check out What is __init__.py for?
Upvotes: 1