2π
In Python, there is a search path for modules. It can be initialized from the command line with the PYTHONPATH
environment variable and accessed programmatically via sys.path
.
By default, the directory of the script you use to start the Python interpreter is the first entry in the search path.
Any module or package on the python path βstarts a new namespaceβ, to use your wording. Letβs assume your project called mysite
has an app called polls
and has this structure:
mysite
βββ manage.py
βββ mysite
βΒ Β βββ __init__.py
βΒ Β βββ settings.py
βΒ Β βββ urls.py
βΒ Β βββ utils.py
βΒ Β βββ wsgi.py
βββ polls
βΒ Β βββ __init__.py
βΒ Β βββ models.py
βΒ Β βββ utils.py
...
If you start it with python manage.py runserver
, the packages mysite
and polls
are available.
Iβd say a good place for project-wide utils module is the project package mysite
. So you do import mysite.utils
in any of your apps. If it grows beyond a single file, you can turn it into a subpackage, so instead of a utils.py
, you have a utils
directory containing an __init__.py
file.
The above structure clutters the global namespace a bit. So some people prefer a structure where all your apps are subpackages of your project package, like this:
mysite
βββ manage.py
βββ mysite
βΒ Β βββ __init__.py
βΒ Β βββ settings.py
βΒ Β βββ urls.py
βΒ Β βββ utils.py
βΒ Β βββ wsgi.py
βΒ Β βββ apps
βΒ Β Β βββ polls
βΒ Β Β Β Β Β βββ __init__.py
βΒ Β Β Β Β Β βββ models.py
βΒ Β Β Β Β Β βββ utils.py
...
3π
From this document:
https://docs.djangoproject.com/en/2.2/ref/applications/#projects-and-applications
Is this snippet:
A projectβs root directory (the one that contains manage.py) is usually the container for all of a projectβs applications which arenβt installed separately.
You can create whatever hierarchy you chose under that directory for utilities, which can conform to pythonβs package
system: