0

I've heard that Python imports can be weird and I feel really stupid for not being able to fix this myself; so please somebody kindly explain how this import situation can possibly be a problem.

Directory structure:

├── main.py
└── sub
    ├── sub1.py
    └── sub2.py

Say sub1 defines function1:

# sub1.py
def function1():
    return "function 1 result"

sub2 imports sub1 and uses function1 in function2:

# sub2.py
import sub1

def function2():
    return f"function 2 result: {sub1.function1()}"

Calling function2 from main.py:

from sub.sub2 import function2

print(function2()

This throws an exception ModuleNotFoundError: No module named 'sub1'.

Why? Shouldn't main.py see sub and sub.sub1 and sub.sub2; and shouldn't sub1 and sub2 see each other?

upgrd
  • 720
  • 7
  • 16
  • try using import sub.sub1 in sub2.py – YUVI_1303 Mar 18 '23 at 13:42
  • Thanks for the swift answer. As a matter of fact this works; import sub.sub1 makes sub.sub1.function1 available in sub2! First of all: thanks! Secondly: Why exactly is that? If I call sub2 with just import sub1 it works, but not from main.py. – upgrd Mar 18 '23 at 13:45
  • 1
    it needs to be in the same level as that of sub1 & sub2 to view it – YUVI_1303 Mar 18 '23 at 13:48

1 Answers1

1

Change sub2.py to this

# sub2.py
import sub.sub1

def function2():
    return f"function 2 result: {sub.sub1.function1()}"

The imports are relative to the main.py. Therefore, the subdirectory sub is required to be part of the import statement even for imports of modules on the same level.

Gosh
  • 13
  • 4
  • Thanks, this works. But now sub2 can't run on its own anymore without throwing an exception... I find this extremely awkward. – upgrd Mar 18 '23 at 13:50
  • 1
    That is true. I would recommend reading this. https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – Gosh Mar 18 '23 at 14:01