Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import modules of parent packages inside child packages

Tags:

python

I have a parent package that has 2 child packages. It looks like this

backend
   __init__.py
   conf.py
   db.py
   connections.py
   /api
      __init__.py
      register.py
      api.py
   /scheduled
      __init__.py
      helpers.py

All the __init__.py files are empty.

The code in backend/connections.py and backend/conf.py is being used by modules in both packages api and scheduled.

in register.py i have code like

from backend.conf import *
from backend.connections import *

Now when i do python register.py i get this error

ImportError: No module named backend.conf

Also when i changed from backend.conf import * to from ..conf import * or from .. import conf i get this error

ValueError: Attempted relative import in non-package

What i understand by the above error is that python is not treating the above folders as packages. But i have __init__.py in all the folders. What is wrong?

like image 833
lovesh Avatar asked Mar 22 '13 12:03

lovesh


1 Answers

When you run python register.py, your backend/register.py file is used as the __main__ module of the program, rather than as a module within the backend package. Further more, the Python import path will not automatically include the directory containing the backend directory, which is probably the cause of your problems.

One option that might work is to run your program as python -m backend.register from the top level directory of your project (or set PYTHONPATH so this module can be found). This will search for the script on the normal import path, and then run it as the main program.

like image 184
James Henstridge Avatar answered Sep 21 '22 03:09

James Henstridge