60

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

Community
  • 1
  • 1
treecoder
  • 43,129
  • 22
  • 67
  • 91

2 Answers2

59

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.

Community
  • 1
  • 1
Eric
  • 95,302
  • 53
  • 242
  • 374
  • 5
    It's discouraged to use `from . import *`. But this does get at the right answer of `from . import mod2` inside `mod1.py`. See https://www.python.org/dev/peps/pep-0328/ – A.Wan Feb 10 '16 at 00:23
  • 7
    I think I meant `*` as a wildcard here, not as literal syntax – Eric Feb 10 '16 at 00:40
  • 1
    `from . import some_module` throws `ImportError: cannot import name some_module` in Python 2.7, with or without `absolute_import` – Jonathan Rys Jan 15 '20 at 22:02
  • You can also do `from .some_module import my_function` to only import the function you want. – Smile Dec 13 '21 at 13:48
4

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.

Diego Navarro
  • 9,316
  • 3
  • 26
  • 33