0

When I use relative imports, my code runs correctly but pycharm moans. In sum.py, the import line is underlined in red and I have no completion.

If I try to switch to use absolute imports by adding "app." everywhere, pycharm is happy but the code doesn't run anymore. I get: "ModuleNotFoundError: No module named 'app'"

Here is the tree structure of my project. It's the content of my test_import folder:

.
-- app
    | -- main.py
    | -- mul.py
    | -- folder
         |-- sum.py

main.py:

from folder.sum import sum, mul_import
from mul import mul

if __name__ == '__main__':
    a=1
    b=2
    print("sum ", sum(a, b))
    print("mul ", mul(a, b))
    print("mul import ", mul_import(a, b))

mul.py:

def mul(a, b):
    return a * b

sum.py:

from mul import mul

def sum(a, b):
    return a + b

def mul_import(a, b):
    return mul(a, b)

Is it possible to use "app." everywhere to have the completion but make the code work?

lovelace63
  • 352
  • 1
  • 6
  • 15
  • 1
    How are you invoking main? and from which directory? – Peter Lindsten Oct 03 '21 at 09:57
  • I am in the root folder of the project. So I run "python app/main.py". – lovelace63 Oct 03 '21 at 10:50
  • Do you have `__init__.py` files? – Peter Lindsten Oct 03 '21 at 11:18
  • I tried with two empty ```__init__.py``` files in the app and folder directories but I still get the message 'No module named 'app''. – lovelace63 Oct 03 '21 at 12:49
  • You can solve this by making the package installable in which case PyCharm will identify the modules from PYTHONPATH. Or you can use the IDE to set the directory as sources root. But whatever the case using relative imports is generally a poor idea because it tends to lead to circular imports. It's advised to use fully qualified names. – bad_coder Oct 03 '21 at 21:40
  • 2
    Does this answer your question? [PyCharm error: 'No Module' when trying to import own module (python script)](https://stackoverflow.com/questions/28705029/pycharm-error-no-module-when-trying-to-import-own-module-python-script) Also see https://stackoverflow.com/q/21236824 – bad_coder Oct 03 '21 at 21:40
  • Thanks for your links, it helped me to look in the right place. I have posted the solution below – lovelace63 Oct 04 '21 at 16:56

1 Answers1

0

In pycharm I have to run with the green arrow and not in command line with "python main.py" or "python app/main.py". This works because the project directory is added to the pythonpath (in the configuration of the run).

For docker I had to add the project directory to the pythonpath.

lovelace63
  • 352
  • 1
  • 6
  • 15