Question

Recently started a new Python project.

I am resolving a import module error where I am trying to import modules from the same directory.

I was following the solutions here but my situation is slightly different and as a result my script cannot run.

My project directory is as follows:

dir-parent
    ->dir-child-1
    ->dir-child-2
    ->dir-child-3
    ->__init__.py (to let python now that I can import modules from here)
    ->module1
    ->module2
    ->module3
    ->module4
    ->main.py

In my main.py script I am importing these module in the same directory as follows:

from dir-parent.module1 import class1

When I run the script using this method it throws a import error saying that there is no module named dir-parent.module1 (which is wrong because it exists).

I then change the import statement to:

from module1 import class1

and this seemed to resolve the error, however, the code I am working on has been in use for over 2.5 years and it has always imported modules via this method, plus in the code it refers to the dir-parent directory.

I was just wondering if there is something I am missing or need to do to resolve this without changing these import statements and legacy code?

EDIT: I am using PyCharm and am running off PyCharm

Was it helpful?

Solution

If you want to keep the code unchanged, I think you will have to add dir-parent to PYTHONPATH. For exemple, add the following on top of your main.py :

import os, sys

parent_dir = os.path.abspath(os.path.dirname(__file__)) # get parent_dir path
sys.path.append(parent_dir)

OTHER TIPS

Python's import and pathing are a pain. This is what I do for modules that have a main. I don't know if pythonic at all.

# Add the parent directory to the path
CURRENTDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if CURRENTDIR not in sys.path:
    sys.path.append(CURRENTDIR)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top