Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a python package

Tags:

python

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"

like image 989
Daniel Walther Berns Avatar asked May 17 '12 22:05

Daniel Walther Berns


3 Answers

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()
like image 56
sarveshseri Avatar answered Nov 04 '22 01:11

sarveshseri


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
like image 38
joemar.ct Avatar answered Nov 04 '22 00:11

joemar.ct


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

from ..Core import a
like image 1
Blender Avatar answered Nov 04 '22 00:11

Blender