Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: importing a module that imports a module

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.

like image 415
Anas Elghafari Avatar asked Apr 14 '13 20:04

Anas Elghafari


1 Answers

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.

like image 199
Martijn Pieters Avatar answered Oct 13 '22 11:10

Martijn Pieters