0

Similar questions have been asked many times, but I can't figure out how to solve it when using IntelliJ.

I have a directory like following

package
├── init.py.
├── subpackage1
│ ├── init.py
│ ├── moduleX.py
├── subpackage2
│ ├── init.py
│ ├── moduleY.py

In moduleY I want import moduleX using relative import syntax: from ..subpackage1 import moduleX

and got the following error message:

attempted relative import beyond top-level package

I know this can be solved by changing the working directory to the top of "package", and typing python -m package.subpackage2.moduleY in the console.

But how can I do it in IntelliJ?

Nina
  • 148
  • 2
  • 16
LtChang
  • 135
  • 12

1 Answers1

0

Following should work:

import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from subPackage1 import fileInSubPackage1

Also, there is a very good explanation on how to deal with imports which can be found here

UPDATE:

Having gone through the official documentation, I realized the reason for above relative import to fail is that when using from something import somefile something should be a package or a number of packages. Below picture will clarify it further:

given this project structure

if we have above project structure, and want to import the_program.py in file_random.py, we have to write from directory_one.package_inside_directory_one import the_program directory_one and package_inside_directory are both packages. and from ..package_two_inside_directory_one import the_program will result in ValueError: attempted relative import beyond top-level package

Now, if the structure is extended to below:

project structure extended

and we're in the_program.py and want to import file_under_Subdirectory.py and more_tests.py we simply follow the same rule:

from directory_two.package_inside_directory_two import more_tests
from directory_two.package_inside_directory_two.subDirectory_inside_package_two import file_under_Subdirectory
Nina
  • 148
  • 2
  • 16