Reputation:
I am getting a little frustrated with python imports at the moment. I think I am honestly just remembering something wrong and performing the import incorrectly.
I have the following directory structure for my application:
open_app
|- __init__.py
|- open_app.py
|- core/
| |- __init__.py
| |- data/
| | |- __init__.py
| | |- data.py
| |- settings/
| |- interface/
|- extensions/
In init.py I have the following:
import open_app.Open_App as Open_App
if __name__ == "__main__":
main = Open_App()
input("Press a key to continue")
In open_app.py I have the following:
from core import data as Data
class Open_App():
pass
In core/init.py, I have nothing.
in core/data/init.py I have the following:
from data import Data as Data
In core/data/data.py I have the following:
class Data():
pass
The problem is that when I run the module using IDLE, I get the following error message:
Traceback (most recent call last):
File "F:\Personal\Code\Python\open_app\__init__.py", line 1, in <module>
import open_app.Open_App as Open_App
File "F:\Personal\Code\Python\open_app\open_app.py", line 1, in <module>
from core import data as Data
File "F:\Personal\Code\Python\open_app\core\data\__init__.py", line 1, in <module>
from data import Data as Data
ImportError: No module named 'data'
I am just trying to get the import to work. So I decided to change the
core/data/init.py file to:
from core.data.data import Data as Data
Which works. But to me this doesn't seem like a very good solution. It doesn't make sense to me to have to prefix all submodules with every module directory above it. It would make it very difficult as the project gets larger to perform a unit test.
Why do I have to prefix the names like that? Since the init.py exists in the
core/data
directory, I should think that:
core/data/data.py
Would be visible and importable. In practice it is not.
What am I doing wrong? I feel very humbled to have to ask thins, and I am sorry that this is basic, but I appreciate any help in advance. I have been reading the PEP documentation on importing and something just isn't clicking.
Thanks in advance!
Upvotes: 2
Views: 2864
Reputation: 78556
If you're going to import data
into __init__.py
without specifying the full path, a relative import is probably what you want:
from .data import Data
Note that the alias Data
you're using is quite unnecessary since the imported object has the same name.
Upvotes: 1