Import modules that are above the project root

I play with the following structure:

http://timmyomahony.com/blog/2012/11/09/general-django-project-structure-or-folder-layout/

Suppose I have some common functions in the lib directory

foo.com < -- site root lib/ django_root/ < -- project root (checked into Github) 

Import, for example:

 from ... lib import my_lib 

Gives me

 ValueError: Attempted relative import beyond toplevel package 
+4
source share
1 answer

I see two clean solutions.

  • For this to work, your lib must be Distutils compatible (have setup.py ). If so, you can simply install it using pip with e- . Just do:

     pip install -e /full/path/to/foo.com/lib/ 

    This will install the library in editable mode, which means that lib will not be installed in site-packages , but will create a symbolic link to the egg there. This means that any changes you make to the files in lib will automatically be transferred to your environment.

  • I do not think this is almost as clean as the first sentence of this. Just add lib to PATH in Django manage.py :

     import os, sys root_path = os.path.abspath(os.path.join(__file__, '..', '..')) lib_path = os.path.join(root_path, 'lib') sys.path.insert(0, lib_path) # ... 
+1
source

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


All Articles