Python : Import modules once then share with several files
Import each of them in a separate module, and then import that:
lib.py
:
import lib7
import lib8
import lib9
In each of the files (file1.py
, file2.py
, file3.py
), just use import lib
. Of course, you then have to reference them with lib.lib7
– to avoid that, you can use from lib import *
.
You will have to import something at least once per file. But you can set it up such that this is a single import line:
The probably cleanest way is to create a folder lib
, move all lib?.py
in there, and add an empty file called __init__.py
to it.
This way you create a package out of your lib?.py
files. It can then be used like this:
import lib
lib.lib7
Depending on where you want to end up, you might also want to have some code in the __init__.py
:
from lib7 import *
from lib8 import *
from lib9 import *
This way you get all symbols from the individual lib?.py
in a single import lib
:
import lib
lib.something_from_lib7