5

I am trying to refactor my code (a bunch of core modules and some apps living in a common directory). I want to get this structure

Root
   __init__.py
   Core
       __init__.py
       a.py
       b.py
       c.py
   AppOne
       __init__.py
       AppOne.py
   AppTwo
       __init__.py
       AppTwo.py
   AppThree
       __init__.py
       AppThree.py

where AppOne.py, AppTwo.py and AppThree.py imports the modules a, b and c in the Core package.

I don't understand how to write the __init__.py files and the import statements. I have read http://docs.python.org/tutorial/modules.html and http://guide.python-distribute.org/creation.html. I got errors like "Attempted relative import in non-package" or "Invalid Sintaxis"

1
  • 4
    you can leave them (the __init__.py) empty and it will work. you only need to put something there if you have particular special requirements (ie want to hide things). Commented May 17, 2012 at 22:43

3 Answers 3

5

You need to add the directory of the python modules to sys path.

If you have something like this

Root
   here_using_my_module.py
   my_module
       __init__.py  --> leave it empty
       a.py
       b.py
       c.py

You need to add you module directory to sys_path

//here_using_your_module.py
import os, sys

abspath = lambda *p: os.path.abspath(os.path.join(*p))

PROJECT_ROOT = abspath(os.path.dirname(__file__))

sys.path.insert(0,PROJECT_ROOT)

import a from my_module

a.do_something()
Sign up to request clarification or add additional context in comments.

1 Comment

This is the point! Thank you very much. I had forgotten to update sys.path.
1

Within AppOne.py:

import os
os.chdir("..")

from Core import a

alternatively, you may write in AppOne.py:

import sys
sys.path.insert(-1,"..")

from Core import a

Comments

1

If you have that exact directory structure, you can use relative imports to import from the parent folder:

from ..Core import a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.