jtcloud
jtcloud

Reputation: 559

Pycharm cannot import module from Parent folder name

I have project defined in below way:

project/
  __init__.py
  dog.py
  cat.py

In my dog.py, I'm calling:

import project.cat

which gives me this error:

ModuleNotFoundError: No module named 'project'

However, I have setup PYTHONPATH to the parent of project directory, which if I run dog.py outside of Pycharm (for example on the command line) it works well without exceptions.

Now even if I added project folder as Source Root, Pycharm still labels my import statement as wrong (red color) and also doesn't allow me to run it inside Pycharm for dog.py program. This is so confusing. Can anyone help?

*PS: I don't want to use relative imports in dog.py like 'from .cat import *' because I have if name == main statement in dog.py, which python doesn't allow me to run the relative imports inside dog.py.

===============

Adding more information:

I noticed if I made the src folder under project to make the structure like:

project/
  __init__.py
  src/
    __init__.py
    dog.py
    cat.py

then I can call this in dog.py:

import src.cat

But this way, I am still troubling myself because when I run program in Pycharm, I have to use this way:

import src.cat

when I run program in ipython notebook, I have to import like:

import project.src.cat

This cause me constantly switch my code when I have to run in different places.

=====================

If I simply do this in dog.py

import cat

It will work in Pycharm. But when I call in command line, it's going wrong there now:

In [10]: import project.dog                                                 
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-10-be5ebc05b4b0> in <module>
----> 1 import project.dog  

~/PycharmProjects/project/dog.py in <module>
      2 import pandas as pd
      3 import numpy as np
----> 4 import cat
      5 from datetime import datetime
      6 

ModuleNotFoundError: No module named 'cat'

Upvotes: 1

Views: 2107

Answers (1)

jtcloud
jtcloud

Reputation: 559

Issue resolved by making my parent folder of my project as the root folder and make root as Source Root.

parent-folder\
  project\
    __init__.py
    dog.py
    cat.py

Now it works well on both command line and Pycharm by simply adding one line in .bashrc:

export PYTHONPATH=$PYTHONPATH:~/project

Upvotes: 2

Related Questions