1

So I'm trying to import a module from package that import its subpackage. Here is sample code:

main_directory
    - main.py
    subdirectory
        - __init__.py
        - test.py
        subsubdirectory
            - __init__.py
            - test2.py

main.py:
    from subdirectory import test
    test.foo1()

test.py:
    from subsubdirectory import test2
    def foo1():
        print("foo1")
        test2.foo2()

test2.py:
    def foo2():
        print("foo2")

in this case, if I change

from subsubdirectory import test2

to

from .subsubdirectory import test2

it works since I guess it's direct path? But when I move to my subdirectory and run python3 test.py it will throw error:

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

Can you explain what happened?

TYN
  • 29
  • 5
  • 1
    See [Attempted relative import in non-package' although packages with __init__.py in one directory](http://stackoverflow.com/questions/14664313/attempted-relative-import-in-non-package-although-packages-with-init-py-in) – Thierry Lathuille Feb 16 '17 at 03:09

1 Answers1

0

If you want to use relative import, you have to run script the package way.

Since there is no __init__.py in main_directory, the package is subdirectory

cd ./main_directory/
python -m subdirectory.test
python -m subdirectory.subsubdirectory.test2

If by any chance, you want the main_directory to be the package name, you have to add __init__.py inside main_directory, then, you run script:

cd ./main_directory/../
python -m main_directory.subdirectory.test
python -m main_directory.subdirectory.subsubdirectory.test2
Gang
  • 2,658
  • 3
  • 17
  • 38