I want to speed up the start time of my Django project’s runserver command, and I’ve started investigating the use of LazyLoader as part of that effort.
If you’re not familiar with it, LazyLoader will “defer” the actual importing of a module until it is access by your code, rather than “eagerly” importing the module right away as Python does by default. If you read the importlib source code, the LazyLoader’s _LazyModule class utilizes the __getattribute__
method to detect when a module is accessed, and performs the import logic within __getattribute__
.
My problem is that the autoreload.py module in Django is accessing all of the modules in sys.modules
to watch for changes so it can perform a reload of the runserver command whenever a module’s contents change. This, in effect, negates the “laziness” of the LazyLoader, and performs an “eager” import anyway whenever the runserver starts.
Does anyone know of a solution to this so I can have real lazy imports in development? Should I report it as a Django bug/feature request?