Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Import modules once then share with several files

Tags:

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?

like image 925
Jet Blue Avatar asked May 24 '16 03:05

Jet Blue


People also ask

Can we import same package twice in Python?

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.

How many times does a module get loaded when imported multiple times in Python?

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.

Does Python import module multiple times?

So import really happens only once. You can adjust this toy example to check cases that are interesting to you.


1 Answers

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 
like image 181
NichtJens Avatar answered Nov 03 '22 07:11

NichtJens