Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently importing modules in Django views

I was wondering - how do people handle importing large numbers of commonly used modules within django views? And whats the best method to do this efficiently?

For instance, I've got some views like,

admin_views.py
search_views.py
.
.

and from what I've seen, every one of them needs to use HttpResponse or other such commonly used modules. Moreover, some of them need things like BeautifulSoup, and others need other things (md5, auth, et al).

What I did when starting the project was to make an include_all.py which contained most of my common imports, and then added these specific things in the view itself. So, I had something like,

admin_views.py

from include_all import *
... 
[list of specific module imports for admin]
...

search_views.py

from include_all import *
... 
[list of specific module imports for search]
...

As time progressed, the include_all became a misc file with anything being needed put into it - as a result, a number of views end up importing modules they don't need.

Is this going to affect efficiency? That is, does python (django?) import all the modules once and store/cache them such that any other view needing them doesn't have to import it again? Or is my method of calling this long file a very inefficient one - and I would be better of sticking to individually importing these modules in each view?

Are there any best practices for this sort of thing too?

Thanks!

like image 912
viksit Avatar asked Aug 02 '26 00:08

viksit


1 Answers

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).

like image 200
Alex Martelli Avatar answered Aug 03 '26 13:08

Alex Martelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!