Search code examples
pythonpycharm

pycharm refactoring yields wrong imports


I am working on a project with a nested project structure shown below.

When I perform any refactoring that involves a change to an import statement, PyCharm generates the import without the top level directory. For example, if a new file needs access to src->domain->money->Currency, it generates:

from domain.money import Currency

but what is needed to run is from src.domain.money import Currency

If I type out "src" manually it runs correctly, but who wants to do that? What is the fix?

Cheers

enter image description here


Solution

  • Currently, your src directory is marked as content root. This way, pycharm will always make imports relative to that root. To "fix" this (it's a feature, because the published part of your package sits in the src directory), you could remove the content root.

    The easiest way to do this, is to right-click the blue src folder and choose "Mark directory as" (bottom-most entry) and "Unmark as sources root".

    enter image description here

    But again, it's a feature, and I would carefully think about why you need to import straight from the bottom of your project instead of from your src root.