Python — import the package in a module that is inside the same package

Question:

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

Asked By: treecoder

||

Answers:

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.

Answered By: Diego Navarro

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.


EDIT:

Looks like from . import some_module will do what you’re after.

Answered By: Eric

It seems like “from . import some_module” works in Python3 only.

The universal way is to do all imports in init.py

Answered By: Dmitry Obukhov
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.