hildensia
hildensia

Reputation: 1740

Pycharm: virtually change name of package

I have a python project, with a source tree like:

|-src
|  |- module1
|  |  |- tests
|  |- module2
|  |  |- tests
|- ...

It will be deployed to a docker as package mypkg, in a way I cannot change -- transparently adding the mypkg folder and __init__.py.

Inside my code I generally import things with import mypkg.module1 or from mypkg.module2 import xyz. However, since there is no mypkg folder (and __init__.py) under src, pycharm does not recognize these imports and reports Unresolved reference errors, and is not able to run pytest against any tests (even though they are not relying on any resource only available within the docker).

Right now for tests I change the imports in the tests from import mypkg.module1 to import module1, run the tests in pycharm, fix bugs, change it back and commit. But as you can imagine this is error prone and annoying.

Is there any way I can tell pycharm or the python environment (maybe $PYTHONPATH to recognize my package as mypkg and act accordingly?

I'm using python 3.5+, exclusively (if that matters).

Upvotes: 1

Views: 45

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43226

In order for both python and your IDE to correctly resolve your imports, you will need to create a directory named mypkg that contains module1 and module2. I can think of two ways to go about this:

1. The correct solution: Fixing the project structure and installation

Rather than creating the mypkg directory during the installation process, have a real mypkg directory inside your src directory:

|-src
|  |- mypkg
|  |  |- module1
|  |  |  |- tests
|  |  |- module2
|  |  |  |- tests
|- ...

(Side note: your tests probably shouldn't be inside your packages. You don't want to ship those, or let the user import them, do you?)

2. The workaround: Symlinks

Create a mypkg directory somewhere on your PYTHONPATH. Then create symlinks to module1 and module2. (How to create symlinks on Windows, How to create symlinks on Linux)

In your project directory:

|-src
|  |- module1
|  |  |- tests
|  |- module2
|  |  |- tests
|- ...

Somewhere on your PYTHONPATH:

|- mypkg
|  |- module1 -> path_to_your_project/src/module1
|  |- module2 -> path_to_your_project/src/module2

Upvotes: 1

Related Questions