Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm can't find import in same folder

Tags:

python

pycharm

enter image description here

I'm using PyCharm and I'm importing some constants from another python file in the same directory. The import works at runtime, but I get this annoying red underline on the import statement and also every time I use a constant from the file.

Here's the file hierarchy

enter image description here

(Please ignore the red underlining on the folders, they are unrelated to this)

What causes this behaviour and how can I fix it?

like image 719
Sahand Avatar asked Jan 08 '19 12:01

Sahand


People also ask

How to import a project from another folder in PyCharm?

Select your working folder and mark it as Sources. Then Pycharm recognize the working folder as a Source folder for the project and you will be able to simply add other files within that folder by using In Pycharm you can simply add . before the .py file which you are going to import it from the same folder. In your case it will be

How do I optimize imports in PyCharm?

Select Optimize imports. To optimize imports in a file, you can also press Ctrl+Alt+Shift+L, select Optimize imports, and click Run. If your project is under version control, you can instruct PyCharm to optimize imports in modified files before committing them to VCS. Press Ctrl+K or select Git | Commit from the main menu.

Why does PyCharm not recognize my project as a source?

The issue is because of how PyCharm sets PYTHONPATH to the root of your project. While you can add directories as Sources, I would not recommended. That will make your project fragile. You can right click pca_mixtures and then mark the directory as Sources Root, this should solve your problem.

Why can't I run PCA_mixtures/funcs in PyCharm?

This doesn't cause issues when running, say, pca_mixtures/funcs.py directly, though. The issue is because of how PyCharm sets PYTHONPATH to the root of your project. While you can add directories as Sources, I would not recommended. That will make your project fragile.


1 Answers

It is better if you replace that with:

from pca_mixtures.constants import *

The issue is because of how PyCharm sets PYTHONPATH to the root of your project.

While you can add directories as Sources, I would not recommended. That will make your project fragile.

like image 102
Juan Leni Avatar answered Oct 07 '22 23:10

Juan Leni