user179169
user179169

Reputation:

Import a module, from inside another module

Basically I have written two modules for my Python Program. I need one module to import the other module.

Here is a sample of my file structure.

test_app 
    main.py
    module_1
        __init__.py
        main.py

    module_2
        __init__.py
        main.py

Main.py is able to import either of the two modules, but I need module_1 to import module_2, is that possible?

Upvotes: 2

Views: 3390

Answers (5)

Macke
Macke

Reputation: 25680

If you add an (empty) __init__.py to test_app, test_app will be a package. This means that python will search for modules/packages a bit smarter.

Having done that, in module1, you can now write import test_app.module2 (or import .. module2) and it works.

(This answer was combined from other comments and answers here, hence CW)

Upvotes: 2

prgbenz
prgbenz

Reputation: 1189

This question ask been answered by the official python documents, in the section called Intra-package References. python modules

The submodules often need to refer to each other. You don't need to care about the PYTHONPATH, declaration of the relative path will do. For your case,

just type "import .. module2" in the module_1/main.py

Upvotes: 1

Arlaharen
Arlaharen

Reputation: 3145

Yes. If your PYTHONPATH environment variable is set to test_app, you should be able to import module1 from module2 and vice versa.

I assume that you run your program like this:

python test_app/main.py

and that the program imports module1.main, which in turn imports module2.main. In that case there is no need to alter the value of PYTHONPATH, since Python has already added the test_app directory to it. See the Module Search Path section in the Python docs.

Upvotes: 1

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29707

If you started your program from test_app/main.py, you can just use from module_1 import main in test_app/module_2/main.py file.

Upvotes: 3

bchhun
bchhun

Reputation: 18474

sure does.

In your module_1 module. In any file:

from module_2 import your_function, your_class

Upvotes: 0

Related Questions