0

I've read PEP 328 and similar questions like this, but they still didn't answer my questions about python 3 import. My question is:

why does a single dot . relative import ever produce an error like the following?

code: (__init__.py exists in the same directory)

from . import module_x

error:

ImportError: attempted relative import with no known parent package

Yes, there are workarounds to get around of this error for example by running python -m from the parent directory, but why?

Shouldn't . always refer to the same directory of the current module and the example always works as long as the module_x exists in the same directory?

Particularly PyCharm tries to run unittest test cases from the directory where the test file is, and would always fail the . import. Some may argue it's PyCharm's problem, but I think a simple import like this should really always work regardless where the interpreter runs.

user1783732
  • 1,599
  • 5
  • 22
  • 44

1 Answers1

0

There is a detailed answer here, also here. Sorry I cannot write this as a comment.

Aurum
  • 53
  • 1
  • 2
  • 11
  • The 1st link is one of the workarounds I looked at. The 2nd link doesn't work for my case. I had to change the `Working Directory` setting in `PyCharm` to point to the parent directory. Nevertheless, I'm wondering why such workarounds are needed for `.` imports. – user1783732 Sep 10 '19 at 19:39
  • That will require a detailed analysis. I remember having the problem with pycharm a year ago, after that I used the package name instead of dot. Relative path imports messed up my project. – Aurum Sep 10 '19 at 19:45