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.

project structure:

├── lawcrawler
│   ├── # import a function from this file
│   ├── lawcrawler
│   │   └── spiders
│   │       └── # import variables from this file
│   │
├── project
│   ├── apps
│   │   ├── laws
│   │       ├── management
│   │           ├── commands
│   │               ├── # import function and variables to this file
│   ├──

I have tried relative import like this:

from .......lawcrawler.lawcrawler.spiders.settings import SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query

and this:

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 could look like this:

import ultraimport
SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query = ultraimport("__dir__/../../../../../lawcrawler/lawcrawler/spiders/", "SPARQL_ENDPOINT, AMENDED_URL_FILE_PATH, get_law_amendment_query")

This will always work, no matter how you run your code.

Back to Top