Vidya
Vidya

Reputation: 209

ImportError: No module named unable to import toplevel directory of module in python

My Directory structure:

├── common
│   ├── common.py
│   └── __init__.py
├── project1
│   ├── __init__.py
│   └── scripts
│       ├── example_import.py
│       └── __init__.py
└── project2
    ├── __init__.py
    └── scripts
        └── __init__.py

I need to import common/common.py module in project1/scripts/example_import.py file

example_import.py:

import sys
sys.path.append("../common")
from common import Test
print("Module Not import error")

Error:

Traceback (most recent call last):
  File "project1/scripts/example_import.py", line 3, in <module>
    from common import Test
ImportError: No module named common

How to fix a issue?

Upvotes: 0

Views: 398

Answers (1)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15588

Understanding how Python imports work is tricky in the beginning but makes sense once you understand how.

There are different way to fix your import issue. I would not recommend messing up with sys.path. Depending on where you are calling your script, you have multiple choice at hand.

Your Directory structure.

├── common
│   ├── common.py
│   └── __init__.py
├── project1
│   ├── __init__.py
│   └── scripts
│       ├── example_import.py
│       └── __init__.py
└── project2
    ├── __init__.py
    └── scripts
        └── __init__.py

On the root of directory

python project1/scripts/example_import.py 

Will work, assuming that the imports in example_import.py looks like

from common.common import Test

If you want to use from common import Test, you need to add from common.common import Test in __init__.py file in common folder.

You can also use PYTHONPATH environment variable to tell Python where to look for the base module.

PYTHONPATH=/pathto/basefolder python folder/filesx.py

Another way is to create a setup.py on base and do development installation python -m pip install --editable . on environment you are working on.

Example of setup.py


#!/usr/bin/env python

from distutils.core import setup

setup(name='projectX',
      version='1.0',
      description='The World is not Enoug',
      author='James Bond',
      author_email='[email protected]',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['common', 'project1', 'project2],
     )

See Python Documentation for more setup.py options.

Upvotes: 2

Related Questions