If Python Packaging is implicit since 3.3, why does my interpreter not treat all subdirectories as packages?

39 views Asked by At

I am barely understanding Python packages.

If packaging is implicit since 3.3, why does this directory structure:

outer_dir/
    outside_main.py
    package_example/
        module_main.py
        tests/
            test_1.py
            …
        level_1/
            foo_1.py
            level_2/
                foo_2.py

With these files:

# module_main.py

from level_1.foo_1 import foo_function_1
from level_1.level_2.foo_2 import foo_function_2


def main():
    print(foo_1())
    print(foo_2())


if __name__ == "__main__":
    main()
# outside_main.py

from package_example.module_main import main

if __name__ == "__main__":
    main()

Give me this error:

Traceback (most recent call last):
  File "/path/to/outside_main.py", line 1, in <module>
    from module_example.module_main import main
  File "/path/to/module_example/module_main.py", line 1, in <module>
    from level_1.foo_1 import foo_function_1
ModuleNotFoundError: No module named 'level_1'

Shouldn't tests/ and level_1 be implicitly treated as sub-packages of package_example/?

Would the situation resolve itself if I littered the directories with indiscriminate __init__.py files?

0

There are 0 answers