I have files as follow,
file1.py file2.py file3.py
Let's say that all three use
lib7.py lib8.py lib9.py
Currently each of the three files has the lines
import lib7 import lib8 import lib9
How can I setup my directory/code such that the libs are imported only once, and then shared among the three files?
Yes, you can import a class twice in Java, it doesn't create any issues but, irrespective of the number of times you import, JVM loads the class only once.
The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.
So import really happens only once. You can adjust this toy example to check cases that are interesting to you.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With