Reputation: 1134
I've been using PyCharm to develop a submodule to drop into several other projects. I have a Tests directory containing my unit tests and I'd like to run them from PyCharm, but when I test any of my code that contains relative imports, I get:
"ValueError: attempted relative import beyond top-level package"
My structure is roughly:
A
____init____.py
...
B
____init____.py
...
Tests
____init____.py
...
Where I am testing a function in the B module that uses relative imports to import A:
from ..A import some_fn
This thread here pycharm and unittesting - structuring project references marking the test directory as such, but when I right click it, I only have the option to mark it as a source root which has no effect.
I also can't really change from relative to absolute imports because it will break my ability to use it as a submodule in other projects. Any advice on how to fix this would be much appreciated.
Update: I also came across this thread How to properly use relative or absolute imports in Python modules? and I'm not a huge fan of the solution (I'd prefer not to have mirror imports in a try/except block), but it does somewhat solve the problem. I would still appreciate a more elegant solution, but if not, that does actually fix the error.
Upvotes: 2
Views: 896
Reputation: 3721
The problem here is that A
and B
are different packages. You want them both to be subpackages of the the myproj
package.
I think all you are missing is a __init__.py
file in the parent directory. Allowing you to relatively import something in B
from something in A
myproj/
├── A
│ └── __init__.py
├── B
│ └── __init__.py
└── __init__.py
Upvotes: 1