3

In a module that I import, I'm trying to import another module, that is located in that same directory.

My files look something like this...

project
├── main.py
└── app
    └── foo.py
    └── bar.py

main.py

import app.foo as Foo

foo.py

import bar

So now, when I run main.py, I get a

ModuleNotFoundError: No module named 'bar'

There are so many similar questions, but none of them seem to be my exact situation.

How can I get this to work?

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
Yarden Akin
  • 71
  • 1
  • 3
  • 2
    `from . import bar` should do the trick, but I'm not sure if this is really the recommended way :) – NiziL Jul 05 '17 at 07:56
  • Possible duplicate of [Absolute vs. explicit relative import of Python module](https://stackoverflow.com/questions/4209641/absolute-vs-explicit-relative-import-of-python-module) – moooeeeep Jul 05 '17 at 08:12
  • Relevant section of the docs: https://docs.python.org/3/tutorial/modules.html#packages and especially: https://docs.python.org/3/tutorial/modules.html#intra-package-references – moooeeeep Jul 05 '17 at 08:20
  • Also related: https://stackoverflow.com/q/14216200/1025391 – moooeeeep Jul 05 '17 at 08:35

2 Answers2

3

Imports from .. or . should work:

from . import bar 

remember to add __init__.py (empty file) inside app directory.

Edit: it could be done only if using foo and bar as modules. E.g. you would not be able to run "python foo.py" or "python foo.bar". Outside of app directory, you could try the code with:

python -m app.foo

(mind the lack of .py extension)

0

This is mainly because when run main.py directly, Python would use the directory where main.py locates as the current running directory, thus when you import bar directly in foo.py, Python interpreter will try to find bar module in that running directory, where bar.py doesn't exist apparently. That is the reason why relative import is needed, as answered by @Robert Szczelina.
If you run foo.py directly, the sentense import bar will be right.

Hou Lu
  • 3,012
  • 2
  • 16
  • 23