2

I am trying to import a submodule withing a seperate submodule using python. Here is my directory structure

enter image description here

I am trying to do this in process_qc.py

from package.database import database
d = database.Database('spark')
print(d.sparkSelect('SHOW DATABASES'))

It gives me error: ModuleNotFoundError: No module named 'package'

asked Jul 20, 2021 at 13:38
11
  • 1
    There is no __init__.py in the package directory. Commented Jul 20, 2021 at 13:39
  • 1
    There is, right above the test folder Commented Jul 20, 2021 at 13:40
  • Ah, I see that now. Are you running process_qc.py from inside that script? Commented Jul 20, 2021 at 13:41
  • app.py is in the wrong place, it should be in the same directory as the readme Commented Jul 20, 2021 at 13:41
  • 1
    You need to call the script from that directory where the readme.md is. If you are calling python process_qc.py from where it is it won't work. But the import should work if it is called by app.py when app.py is in the right placek Commented Jul 20, 2021 at 13:43

2 Answers 2

2

You can try doing this with relative imports:

from ..database import database
answered Jul 20, 2021 at 13:48
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works. i was looking for an absolute import method to work as well.
I added it to the answer! Does that work for you? Edit: woops, I did it wrong. No time do dive deeper into it right now, sorry.
1

Python does not know where package exists when you use an absolute import. This is because Python first looks in the built-in modules and then at directories listed in sys.path for the requested import. If the import is not found, the current working directory is prepended to sys.path.

To use absolute imports, you should either:

  1. Execute the script from outside the package directory so that the package directory is discoverable from a path listed in sys.path.
  2. Add the package directory to your PYTHONPATH:
$ export PYTHONPATH=$PYTHONPATH':path/to/package'
answered Jul 20, 2021 at 14:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.