How to import a function or variable from a sibling of the current parent app 5 levels upper of the current app in Django?
I want to import some functions a constants variables from 5 levels upper of the current app of Django application.
My problem is that the package that I want to import from, is outside of the Django application, so Django isn't aware of it.
├── lawcrawler │ ├── get_all_amended_laws_urls.py # import a function from this file │ ├── lawcrawler │ │ └── spiders │ │ └── settings.py # import variables from this file │ │ ├── project │ ├── apps │ │ ├── laws │ │ ├── management │ │ ├── commands │ │ ├── add_list_of_amended_laws.py # import function and variables to this file │ ├── manage.py
I have tried relative import like this:
from .......lawcrawler.lawcrawler.spiders.settings import SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query
from .....lawcrawler import get_all_amended_urls
but got this error:
ImportError: attempted relative import with no known parent package
How to import the functions and variables or solve this issue?
I've had similar problems in the past because Python does not allow relative imports in scripts. They only work if you run a module. Thus I've created a new import library: ultraimport which gives the programmer more control over their imports.
It allows to do file system based imports with relative or absolute paths. Your add_list_of_amended_laws.py could look like this:
import ultraimport SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query = ultraimport("__dir__/../../../../../lawcrawler/lawcrawler/spiders/settings.py", "SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query")
This will always work, no matter how you run your code.