2

I have got a problem with relative import while developing an application that contains two packages I implemented, one for functionality and other for GUI.

Here's the actual application "architecture" layout:

 main.py  
 functionality/  
     |__init__.py  
     |functionality.py  
     |config/  
         |__init__.py  
         |conf.py  
 gui/  
     |__init__.py  
     |gui.py

I import the config module inside the functionality.py file and use it without any problem. But when I import the functionality module to the main.py file and run it, I get the following error:

from config import conf
ImportError: No module named 'config'

I have searched for this problem and read several Python books, but I didn't find any solution.

Thank you in advance!

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
Youssef11
  • 29
  • 7

2 Answers2

0

As I understand you, you tried to import functionality.functionality, which imports config, and that fails.

That's because when you run main.py, in your module search path there is no modules containing anything like 'config'. Check that out: add

import sys
print (sys.path)

right before you imported functionality. There is root in your search path (where main.py is located) and some default site directories.

Refer to this section: https://docs.python.org/3/tutorial/modules.html#intra-package-references

As it written there, you have to use relative imports (with leading dots) or write full path (functionality.config in your case)

  • You are right, I should use relative imports and that's what works, the full path solution also works. The second solution throws another error: __ImportError: No module named 'functionality.config'; 'functionality' is not a package__ – Youssef11 Dec 02 '15 at 19:14
  • Yes, you can't directly use a module with a local import. – Nikita Kipriyanov Dec 02 '15 at 19:18
  • Also, I should specify that those errors occur when I run _functionality.py_ alone; unlike _main.py_ which runs fine even with importing functionality package. – Youssef11 Dec 02 '15 at 19:23
-2

I found the solution!

I added a leading dot the faulty import statement in functionality.py file:

from .config import conf

It works just fine when running the main.py file!
But let's say that I reversed the problem because now the import doesn't work when I run the functionality.py alone the interpreter throws the same exception

Traceback (most recent call last):
File "/home/youssef/workspace/application/functionality/functionality.py", line 14, in <module>
from .config import conf
SystemError: Parent module '' not loaded, cannot perform relative import

I must also mention that I emptied the __init__.py file that exists in the config package so it doesn't contain any import statement.

I thank you all for your efforts and if I find other solutions, I will edit this answer.

Youssef11
  • 29
  • 7