Reputation: 45081
I have a project structure something like this...
/some_app
build/
README
out.py
some_app/
__init__.py
mod1.py
mod2.py
Now I want to import some_app
package into mod2
, without messing with sys.path
trickery. What I simply did is...
# mod2.py
import some_app
Now when I run the mod2.py from the command line
some_app $ python mod2.py
it throws error ImportError: No module named some_app
BUT, inside the out.py
file, when I do
# out.py
import some_app.mod2
and then do
some_app $ python out.py
it runs perfectly.
Hence, what is happening is this. I load a package in a module that is within the same package, and then run that module as the __main__
file -- and it doesn't work. Next, I load the same module (the one that I ran as __main__
) inside another module, and then run that another module as __main__
-- and it works.
Can someone please elaborate on what's going on here?
UPDATE
I understand that there is no straightforward reason for doing this -- because I could have directly imported any modules inside the some_app
package. The reason I am trying this is because, in the Django project, this is what they're doing. See this file for example
In every module, all the non-standard imports start with django.
. So I wondered why and how they are doing that.
UPDATE 2
Relevant links
Upvotes: 65
Views: 104835
Reputation: 51
You can install your package locally in your virtual environment by running pip install -e .
That should fix the problem. Once you install the package using pip, you can use it by its name.
Flag Description:
-e, --editable <path/url> Install a project in editable mode (i.e.
setuptools "develop mode") from a local project
path or a VCS url.
Don't forget to configure pyproject.toml
or setup.py
Upvotes: 1
Reputation: 97575
mod2.py
is part of some_app
. As such, it makes no sense to import the module, since you're already inside it.
You can still import mod1
. I'm assuming you need some_app/__init__.py
to run. Not sure that's possible.
Looks like from . import some_module
will do what you're after.
Upvotes: 65
Reputation: 9704
You can do import some_app.mod2
from out.py
because it is in the same directory that you have some_app
package, and Python interpreter starts to look for modules from that path.
The import error in mod2.py
is normal because there is not a some_app
package in mod2.py
folder.
Upvotes: 4