2

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.