views:

345

answers:

3

Hi all,

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!

+3  A: 

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

Alex Martelli
Ah that was another follow up question I was going to ask - specifically using from ... * and import *.. Thanks!
viksit
@viksit, you're welcome!
Alex Martelli
A: 

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

phillc
A: 

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.

Javier