17

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?

1
  • The same thing happens for me when I'm editing a file inside a subdirectory of a project. This doesn't cause issues when running, say, pca_mixtures/funcs.py directly, though. Commented Jan 8, 2019 at 12:33

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

first, it didn't help me as the error still shows, second - i don't think its best practice since your project might have colliding constants one day (like we did ) when you import everything you have no control.
13

You can right click pca_mixtures and then mark the directory as Sources Root, this should solve your problem. Good luck!

4 Comments

Can one have multiple source roots?
If you mean to set multiple sub-directories in a directory as sources root, the answer is yes, it's possible.
Here you can also find another confirmation of proper solution for your issue: (intellij-support.jetbrains.com/hc/en-us/community/posts/…)
Thank you, fixed the problem for me.
-3

You can use from .constants import *. Always check if you're able to control+click/ cmd+click to your imported file

1 Comment

I tried this before and it gives an ImportError: attempted relative import with no known parent package message.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.