How to write a python package

I am trying to reorganize my code (a bunch of core modules and some applications living in a shared 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 import modules a , b and c into the Core package.

I do not understand how to write __init__.py files and import statements. I read http://docs.python.org/tutorial/modules.html and http://guide.python-distribute.org/creation.html . I got errors such as "Attempting to import relative to a non-package" or "Invalid syntax"

+4
source share
3 answers

You need to add the python modules directory to the 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 the 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() 
+4
source

Inside AppOne.py:

 import os os.chdir("..") from Core import a 

you can write in AppOne.py:

 import sys sys.path.insert(-1,"..") from Core import a 
+1
source

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

 from ..Core import a 
+1
source

Source: https://habr.com/ru/post/1413074/


All Articles