[Django]-Python / django, where is the root of the namespace?

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
...
πŸ‘€Daniel Hepper

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:

https://docs.python.org/3/tutorial/modules.html#packages

πŸ‘€davejagoda

Leave a comment