3

Lets say I have the following folder structure:

project/
    a.py
    module/
        b.py
        c.py
        __init__.py

a.py needs to import b.py, so it should include from module import b

b.py needs to import c.py, so it should include simply import c since they are in the same folder. But this throws a ModuleNotFoundError when a.py is run.

If I switch the line in b.py to be from module import c then a.py will run, but if I try to run b.py on its own it throws ModuleNotFoundError.

what is the correct way to import in Python?

MannerPots
  • 67
  • 5
  • Depending on Python version and `__future__` a `import c` is interpreted as absolute import which is based on a directory in `PYTHONPATH` or the script called in the `python` command. You need a relative import then. – Michael Butscher Apr 20 '18 at 19:14

1 Answers1

1

In python 3 try using:

from . import c

on your module/b.py file.

This forces the interpreter to look in the local folder for the module.

You wont be able to run your b module (at least not with python module/b.py), if you need it to be an executable, maybe look at:

Relative imports in Python 3

As sugested, for running your b module you can do

python -m module.b

from the parent folder.

DSLima90
  • 2,680
  • 1
  • 15
  • 23
  • Ok, thanks. I had wanted the `b.py` file to provide some functionality if it was run as main instead having to run `a.py` every time, but it looks like that isn't possible. I guess the solution is to put that functionality in a script like `b_main.py` instead. – MannerPots Apr 20 '18 at 19:36
  • You can use global imports, as in `from module import c` and add the folder that contains you module folder to your PYTHONPATH. That is a possible way to do it. – DSLima90 Apr 20 '18 at 19:48