My question originally was raised by an error, highlighted here. The original issue is now solved, but this leaves a question about how importing works in Python. Here are the quick steps to reproduce the issue with Django:
- Launch a dummy project with django-admin
- Create an app with it:
./manage.py startapp dummy_app
In the app
models.py
define a function and a class that extends Django model, as below:from django.db import models # auxiliary function in models def aux_function(value): print(value) class Report(models.Model): class Meta: managed = False
In the new app module's
__init__
, import the mentionedaux_function
as below:from dummy_app.models import aux_function
- Add application to
INSTALLED_APPS
and run dev server
It will result in an exception:
File "/home/aanikeev/PycharmProjects/dummy/dummy_app/__init__.py", line 1, in <module>
from dummy_app.models import aux_function
File "/home/aanikeev/PycharmProjects/dummy/dummy_app/models.py", line 8, in <module>
class Report(models.Model):
File "/home/aanikeev/.virtualenvs/dummy/lib/python3.5/site-packages/django/db/models/base.py", line 110, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/aanikeev/.virtualenvs/dummy/lib/python3.5/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
self.check_apps_ready()
File "/home/aanikeev/.virtualenvs/dummy/lib/python3.5/site-packages/django/apps/registry.py", line 125, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
Which is OK, we know from documentation that we shouldn't import models or modules with them before Django initializes (see ref 1, ref 2). What is not clear to me is why importing a function from a module causes implicit import of a class in the same module (this is exactly what happens, because the mentioned exception derives from a constructor of a Model meta class)?