Django: import causes ImportError only when in try except block

Viewed 139

I have two modules that import some stuff from each other:

project/urls.py:

from modules.helpers import helper

urlpatterns = [
    # patterns
]

modules/helpers.py:

def helper():
    # some magic

def main():
    from project.urls import urlpatterns
    # process urlpatterns

modules/__init__.py:

from modules.helpers import main
main()

And everything works fine, until I wrap from project.urls import urlpatterns to look like this:

def main():
    try:
        from project.urls import urlpatterns
    except Exception as e:
        print(str(e))

It prints:

cannot import name 'urlpatterns' from partially initialized module 'urls' (most likely due to a circular import) (/Users/MaxCore/Documents/www/project/project/urls.py)

What can be the reason?

EDIT

In minimal reproducible example everything also works fine, probably exception is related to django somehow. Something changed in import order because of try except block


If I specify modules in settings.INSTALLED_APPS (which is not needed), and runserver it prints:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

1 Answers

I still do not understand the deep reason behind why try-except block changes load order, but I've found a solution:

  1. Add modules to settings.INSTALLED_APPS
  2. Create apps.py in modules/ dir with content:
from django.apps import AppConfig

class ModulesConfig(AppConfig):
    name = 'modules'

    def ready(self):
        from module.helpers import main
        main()
  1. Add default_app_config = 'core.apps.ModulesConfig' to modules/__init__.py
Related