Question

Python does not automatically import subpackages or modules. We have to do it explicitly, But why Django automatically import submodule of a package.

users/
    __init__.py (empty file)
    models.py
    views.py

in Django's Python manage.py shell:

    >>>import users
    >>>users.models.User     (will not throw AttributeError: 'module' object has no attribute)

But when not in Django:

package1/
    __init__.py (empty file)
    module1.py
    >>>import package1
    >>>package1.module1  
    AttributeError: 'module' object has no attribute 'module1'

Can anyone explain the differences? Thank You

Was it helpful?

Solution

The manage.py script sets up your Django environment before passing control to the Python shell. The shell is not a separate invocation of the python executable; it is executed by the same Python interpreter running the manage.py script itself. At the point where the shell is invoked, Django has already loaded its configuration and initialized all enabled applications, so all of their models.py submodules are already loaded.

When the same module is imported in several locations (e.g. import users), it is not loaded multiple times; the module instance itself will be the same in all places it is imported. Since Django itself has already imported users.models during its initialization, the existing users module instance already contains a reference to the already imported users.models submodule, and you can access it right away without importing it explicitly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top