Python : Import modules once then share with several files

Question:

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?

Asked By: Jet Blue

||

Answers:

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 *.

Answered By: Rushy Panchal

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
Answered By: NichtJens
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.