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?

Jet Blue
  • 5,109
  • 7
  • 36
  • 48
  • See [this answer](http://stackoverflow.com/questions/44834/can-someone-explain-all-in-python) and consider creating a single `mylib.py` file that imports all three libraries, then publishes the symbols you want via `__all__`. – aghast May 24 '16 at 03: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 '16 at 03: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 '16 at 03:46

2 Answers2

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
NichtJens
  • 1,709
  • 19
  • 27
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 *.

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94