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?

7
  • 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? docs.python.org/3/reference/… Commented Dec 14, 2020 at 21:06
  • Updated the question with the error message NameError: name 'package2' is not defined. Commented Dec 14, 2020 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. Commented Dec 14, 2020 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. Commented Dec 14, 2020 at 23:29
  • @Steve : So we can assume it exists at that location, right? Commented Dec 14, 2020 at 23:30

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Yes it works, but you're right -- I need to import both the package and the module when using the partial path notation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.