简体   繁体   中英

Does 'from module import function' statement cause implicit imports of other functions in given module

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:

  1. Launch a dummy project with django-admin
  2. Create an app with it: ./manage.py startapp dummy_app
  3. 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 
  4. In the new app module's __init__ , import the mentioned aux_function as below:

     from dummy_app.models import aux_function 
  5. 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)?

In order for any object in a module to be imported, the entire module must be imported and run. Python makes no distinction between definitions and other code - all code is executable, so the entire file must be executed in order for the object to be defined so that it can be imported. If that execution includes calls to import other files, those imports will also be executed (which can at times lead to circular import dependencies). Similarly, if there is any other code at module level that access the database, or prints to the console, that will also be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM