[Django]-Efficiently importing modules in Django views

6đź‘Ť

âś…

Python itself guarantees that a module is loaded just once (unless reload is explicitly called, which is not the case here): after the first time, import of that module just binds its name directly from sys.modules[themodulename], an extremely fast operation. So Django does not have to do any further optimization, and neither do you.

Best practice is avoiding from ... import * in production code (making it clearer and more maintainable where each name is coming from, facilitating testing, etc, etc) and importing modules, “individually” as you put it, exactly where they’re needed (by possibly binding fewer names that may save a few microseconds and definitely won’t waste any, but “explicit is better than implicit” — clarity, readability, maintainability — is the main consideration anyway).

0đź‘Ť

I guess you could slap your frequently used imports into your __init__.py file.

0đź‘Ť

Django isn’t CGI (or PHP). Your app is a single (or a few) long-running Python process. It doesn’t matter how long it takes to start, each HTTP request will simply call your (already loaded) view functions.

Leave a comment