4

Why PyCharm underlines these imports:

from oauth2_helper import (_url, get_token, get_session)
from config import scope

as Unresolved reference, but if I add dots in front:

from .oauth2_helper import (_url, get_token, get_session)
from .config import scope

I don't get the error underline in PyCharm, but when running my app from terminal, I get this error:

ModuleNotFoundError: No module named '__main__.oauth2_helper'; '__main__' is not a package

What do you think, why is this happening?

Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57
Ignas
  • 389
  • 2
  • 13
  • 3
    Did you select the directory you run your app from terminal as the `Sources Root`? (Right click on the folder you want to be the root and click `Mark Directory As -> Sources Root`) The Root folder should have a blue icon. Then PyCharm will autocheck the imports from this defined root. – Eskapp Nov 19 '18 at 18:58
  • Post it as answer, it is solution to problem. – Dinko Pehar Nov 22 '18 at 20:39

1 Answers1

2

There are two things at play, here:

Like Eskapp says in the comment, PyCharm is configured to a different Project Root than you seem to expect, as evidenced by it marking your imports as unresolved references. You didn't provide any hints to your project structure, but its likely that your Project Root is set to the parent directory of your Python module (or even further up the hierarchy). PyCharm is looking for ${PROJECTROOT}/oath2_helper and isn't finding it, because Project Root is set to the wrong directory.

You then try to fix this problem by changing to relative imports, which seems like a logical solution. It looks like you're directly calling the module in which those imports are written (i.e. python myapp.py). When you call a module in this way, it drops information about the package structure, and no longer has any information about where other modules are relatively located. See https://stackoverflow.com/a/73149/11034626

C Reid
  • 56
  • 1
  • 5