Relative imports breaking run/debug mode

Answered

Hi

I have a project dir set up as following:

 

project/

   package/

        __init__.py

        webapp.py

        data_api.py

 

In web app I have some relative imports from data_api.py e.g.

 

from .data_api import func1, func2

 

This runs fine from the project dir using(no explicit PYTHONPATH set):

python -m package.webapp

However, if I run or debug webapp from pycharm I get:

...

ModuleNotFoundError: No module named '__main__.data_api'; '__main__' is not a package

This happens even if I mark package as the 'Sources Root' and add both the sources and content root to the PYTHONPATH in the run config.

 

This post seemed to suggest that would work:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000729284-Relative-import-from-within-a-Python-Package-?flash_digest=bbefc9eb271760bf0e81a051f7e6049bcd3335ea

But presently I can't get debug/run mode to work within pycharm.

Thanks

Nathan

 

 

 

 

7 comments

Hi, do you use a module target in the run configuration?

0

I don't have the 'Module name' parameter available in the config. Is this available in CE?

0

Yes indeed, which PyCharm version do you use?

0

To let 'Module name' appear, you should mark you package as 'source root'. Just right click your package folder, and jump to "Mark Directory as". By default, you will see "Script path" instead of "Module name" in the configuration window, just switch it. Hope it helps

1

There is a drop down on 'Script path', that's the bit I was missing. Thanks!

Have now configured and applied that in the run config, but when I try and run it, the menu now shows:


Running this, creates a new run config, which does not have my new module name configured. I cannot get pycharm to run with the old/edited config.

If I edit the new config, pycharm then tries to run with a new 'webapp (2)' config.

 

0

Figured it out now, if I right click the webapp.py in the project window, then it always tries to run with a new config. However, my old edited config is available in the toolbar run drop down.I have to say, that is really confusing. Surely the right click 'run' should be 'Run New Config'. 

Thanks for the help guys.

 

0

Please sign in to leave a comment.