3

My project has this kind of structure:

mypackage
|
|-- __init__.py
|
|-- file.py
|
|-- subpackage
 |
 |-- __init__.py
 |
 |-- function.py

How do I import the modules in the subpackage from file.py?

I tried a couple of things like simply import subpackage or from subpackage import function but all of them lead to ModuleNotFoundError: No module named 'subpackage'.

from . import subpackage has no error message but I don't know how to access the module with that.

asked Apr 3, 2021 at 12:03
2
  • This should work fine. What is the error message you get when you use from subpackage import function Commented Apr 3, 2021 at 12:07
  • Regarding how to access, you can do subpackage.function() on a separate line to call a specific function Commented Apr 3, 2021 at 14:03

2 Answers 2

2

I solved it by using:

from mypackage.subpackage import function 
answered Apr 3, 2021 at 13:22
Sign up to request clarification or add additional context in comments.

1 Comment

Explicit is always better than implicit.
0

Just use

from subpackage import function

You propably are not in mypackage directory

answered Apr 3, 2021 at 12:08

3 Comments

Thanks for your answer but when I type ´from subpackage import function´ in file.py I get: ModuleNotFoundError: No module named 'subpackage'
You have to run file.py from mypackage directory
For a bit more explicitness, I recommend from .subpackage import function

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.