5
votes

So in a file foo I am importing modules:

import lib.helper_functions
import lib.config

And in helper_functions.py, I have:

import config

When I run the main function of foo I get an ImportError

EDIT: Here is the structure of the files I have

foo.py
lib/
    config.py
    helper_functions.py

The error results from importing config in helper_functions

Traceback (most recent call last):
  File "C:\Python33\foo.py", line 1, in <module>
    import lib.helper_functions
  File "C:\Python33\lib\helper_functions.py", line 1, in <module>
    import config
ImportError: No module named 'config'

So: when I run foo.py the interpreter is complaining about the import statements of helper_functions. Yet when I run the main of helper_functions, no such error appears.

2
You need to import modules in every other file that uses them; each module gets its own namespace and doesn't inherit the names in the files it imports (unless you use the from foo import * syntax which you should avoid as it leads to horrible, hard-to-diagnose bugs) - Wooble
If you're saying I need to import config in foo, I am already doing that (of course in foo I have to refer to it as lib.config) It's not helping with the NameError. - Anas Elghafari
I don't see a NameError in your traceback. I see an ImportError, that is a very different error. - Martijn Pieters
Thanks for note, I actually re-produced the original setup minimally before I added the recent edit. So there was a NameError in my code, but that was coming from somewhere else. I guess I should edit it since it's not part of this particular problem. - Anas Elghafari

2 Answers

7
votes

You need to import config using an absolute import. Either use:

from lib import config

or use:

from . import config

Python 3 only supports absolute imports; the statement import config only imports a top level module config.

0
votes

In python each module has its own namespace. When you import another module you are actually only importing its name.

The name "config" exists in the module helper_functions because you imported it there. Importing helper_functions in foo brings only the name "helper_function" into foo's namespace, nothing else.

You could actually refer to the "config" name in foo.py with your current imports by doing something like:

lib.helper_functions.config

But in python is always better to be explicit rather than implicit. So importing config in in foo.py would be the best way to proceed.

#file foo.py
import lib.helper_functions
import config