0

I have this directory structure:

├── package1
│   ├── __init__.py
│   └── package2
│       ├── __init__.py
│       └── module2.py
└── script.py

The script.py file looks like this:

import package1.package2.module2
import package1.package2

if __name__ == '__main__':
    package1.package2.module2.run()  # This works
    package2.module2.run()           # This fails

Execution fails with this error, NameError: name 'package2' is not defined.

How can I change the code in such a way that package2.module2 is recognized as an imported module?

Steve
  • 1,250
  • 11
  • 25
  • have you tried using the leading dot notation from the docs? I don't see why what you have laid out wouldn't work. what's the error? https://docs.python.org/3/reference/import.html#package-relative-imports – willwrighteng Dec 14 '20 at 21:06
  • Updated the question with the error message NameError: name 'package2' is not defined. – Steve Dec 14 '20 at 23:12
  • @Steve : It seems that there is no `package2` directory with a `module2` file in it. That may be the reason of the error. – Lakshya Raj Dec 14 '20 at 23:22
  • @LakshyaRaj Understood. The reason for the original question is to enhance readability with a partial path, without becoming too verbose with the full path. – Steve Dec 14 '20 at 23:29
  • @Steve : So we can assume it exists at that location, right? – Lakshya Raj Dec 14 '20 at 23:30
  • This SO post may help: [link](https://stackoverflow.com/questions/50810656/python-folder-structure-for-project-directory-and-easy-import) It seems like there may be submodule conventions that you're deviating from (see Michael liv. answer) – willwrighteng Dec 14 '20 at 23:32
  • @wim yes, that works. Make this an answer and I will mark it accordingly. – Steve Dec 15 '20 at 00:15

1 Answers1

1

This script.py is bugged for expecting the package2 name to just appear out of nowhere - the import statements shown only bring the name package1 into the namespace.

It could use from package1 import package2 instead, so that package2 is in the namespace. In this case, importing the module2 separately is still required.

Most typical would be a single import statement:

from package1.package2.module2 import run

if __name__ == "__main__":
    run()
wim
  • 338,267
  • 99
  • 616
  • 750
  • Yes it works, but you're right -- I need to import both the package and the module when using the partial path notation. – Steve Dec 15 '20 at 00:24