0

I am trying to understand how a lower level package 'knows' about a higher level module such that calling it doesn't result in an error. My directory structure is as follows:

.
├── foo.py
├── script.py
├── pkg
│   ├── __init__.py

My file contents are as follows:

foo.py contains:

class Foo():
    print("foo")

pkg/__init__.py contains:

from foo import Foo

script.py contains:

from pkg import Foo

foo = Foo()

From the directory where script.py is located, I can run python script.py and it results in "foo" being printed.

How is pkg/__init__.py able to successfully import Foo even though foo.py is located in a higher level directory?

Nevermore
  • 318
  • 2
  • 11
  • Does this answer your question? [What is \_\_init\_\_.py for?](https://stackoverflow.com/questions/448271/what-is-init-py-for) – Marco Bonelli Jan 10 '22 at 22:09
  • I searched through the information there, but I have not found any examples or explanations relating to a module importing something from a higher level directory yet. – Nevermore Jan 10 '22 at 23:03
  • are you running your script through some IDE like pycharm or through terminal? and another way is to check is `import sys print(f"The module search path is : {sys.path}")` , usually IDE adds project folder in the path. – simpleApp Jan 10 '22 at 23:18
  • I'm just running it through terminal, no IDE. Yeah, the first path in sys.path is indeed the top level directory where script.py is located. – Nevermore Jan 10 '22 at 23:34

0 Answers0