32

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?

3
  • See this answer and consider creating a single mylib.py file that imports all three libraries, then publishes the symbols you want via __all__.
    – aghast
    May 24, 2016 at 3:23
  • 8
    In case you're worried about modules being imported multiple times in the same file, Python loads the imported file into the namespace only once. Any subsequent imports of the same file will not be loaded.
    – hhbilly
    May 24, 2016 at 3:27
  • 1
    @hhbilly Didn't know that, thanks! That was part of what I was worried about. The other was repetitive code.
    – Jet Blue
    May 25, 2016 at 3:46

2 Answers 2

26

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
9

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.