1

I'm trying to import a class from a script that is located in another package:

project_folder | | package_1 | | __init__.py | |foo.py | | | package_2 | | __init__.py | | bar.py 

In the script: "bar.py", I have the following import:

from package_1.foo import Class 

This line generates the error:

ModuleNotFoundError: No module named 'package_1' 
2
  • What does instance refer to? How do you start your script (what command)? Commented Oct 12, 2020 at 11:18
  • I simplified the code, however forgot to change the module name. I have changed the description. I start my code by python bar.py. Commented Oct 12, 2020 at 11:20

1 Answer 1

1

If you are running the code from the package_2 directory then package_1 is not in your path so there is no knowledge of it to the interpreter.

From the project_folder directory you could run python -m package_2.bar and then it will be in your path.

By path I mean the environment variable that is the list of directories the python interpreter looks for packages. By default it is some places relative to where you have python installed + the current directory. You could manually update this variable to be whatever you want (See https://docs.python.org/3/install/index.html#modifying-python-s-search-path) but the most consistent way to run what you are describing is to run it from the directory above.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.