Think about it your are inside my_file.py
and import something called devices
.
How can python
know where the name devices
has come from.
It won't search your entire Drive for that module/package
Relative Import
use a relative import instead. write from ..devices.models import Device
. This is telling python to go up one directory to the parent directory and that's where it will find the devices
package. Your lib
module should now work as a module
If you however run the my_file.py package directly (as in python C:/django_vue/lib/my_file.py
)
You will still get an error. Not the same error; the new error will be something like
ImportError: attempted relative import with no known parent package
This is happening because you are actually running my_file.py
If you think about it why would you want to run my_file.py
by itself when it is clearly a part of a package. Maybe you are just testing to see if the import works when you use your package. The problem with this is that it makes it seem like your packages relative imports don't work even though this actually works.
Create a main.py
in django_vue and write from lib import my_file
. This will run your my_file.py
and you will notice there is no error.
What's happening here
Have you heard of __package__
?
if you put print(str(__package__))
in your my_file.py
and run my_file.py
directly you will see that it prints None
.
However if you run main.py
(that you just created) you will see that when It reaches my_file.py
, __package__
will actually be defined to something.
Ahhh... you see now it all makes sense; The error you originally got said something about no known parent package
. If __package__
is undefined that means there is no relative parent package because the file was obviously run directly instead of as part of a package.
Consider Absolute imports
you also might want to consider using absolute imports because if you are working on the package you might change it directory structure while developing. so you need to keep changing the import references on the affected files.
Although you can find IDE's with python extensions that automatically to this as you change your directory. I believe VS Code
does this automatically.