Python3 relative import IDE - Debug/Run issues

Issues with relative imports when using python3

In the same folder I have

package1.py

```

def hello_import():
print('hello_import')

```

 

package2.py

```

from .package1 import hello_import


def use_package1():
hello_import()


if __name__ == '__main__':
use_package1()

```

 

If I use "from .package1 import hello_import" the IDE recognizes the package and the import, but I get 
ModuleNotFoundError: No module named '__main__.package1' error when trying to debug or run the code

If I use "from package1 import hello_import" (without the period before the package name) the IDE does not recognizes the package and the import,
but now the  Debug/Run works well.

 

I can do

```

try:
from .package1 import hello_import
except Exception as e:
from package1 import hello_import


def use_package1():
hello_import()


if __name__ == '__main__':
use_package1()

```

 

but this does not look to me as a professional solution.   
Any suggestions on how to solve this?

I am using:   

  • Python 3.6.4
  • pycharm pro 2020.2
  • linux

thanks

 

4 comments
Comment actions Permalink

>In the same folder I have

Try marking this folder as source root from project structure settings, does it help?

0
Comment actions Permalink

It is already in the project structure and the working directory

0
Comment actions Permalink

I'm not sure we're on the same page.

I mean, right click on the directory with python files in project view and select "mark as sources root". Does the issue reproduce afterwards? Could you please show a screenshot (the whole IDE window) ?

0
Comment actions Permalink

Yes, if I right-click on directory and select "mark as sources root" it does fix the issue
and I noticed that I can select "mark as sources root" for several directories in the project

Thanks

0

Please sign in to leave a comment.