Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : how to import module in other module

I have following directory structure

outdir
     |--lib
            |--- __init__.py
            |--- abc.py
     |--indir
            |--- __init__.py
            |---- import_abc.py

How to import lib in import_abc.py?

when i try to import lib in import_abc.py

I get following error

  Traceback (most recent call last):
  File "import_abc.py", line 1, in <module>
  import lib
  ImportError: No module named lib
like image 828
Nikhil Rupanawar Avatar asked Sep 11 '25 08:09

Nikhil Rupanawar


1 Answers

Take a minute to look at what you're trying to achieve: you want to import the module abc.py which is a part of the package lib, so in order to import it correctly you need to specify in which package it is:

from lib import abc

or

import lib.abc as my_import

On a side note, have a look at the Python Tutorial chapter on modules.

Given what @Noelkd commented, I forgot to tell you about PYTHONPATH which is an environment variable that contains the folder where Python will look for the module (like the Java CLASSPATH). You need to put your root folder inside the PYTHONPATH to avoid doing some fiddling with sys.path.append.

In Bash:

export PYTHONPATH=<abs. path to outdir>

For example, I've put outdir in my Desktop:

export PYTHONPATH=~/Desktop/outdir

And the import works like a charm.

You can find some great explanations of the import mechanism and PYTHONPATH in this blog post.

N.B.: If you're using an IDE (PyDev for example), generally it will set up the PYTHONPATH automatically for each project. But if you want to do it all by yourself, you will need to set the PYTHONPATH environment variable.

like image 83
Ketouem Avatar answered Sep 12 '25 23:09

Ketouem