This might seem like a subjective question, but I'm sure there are good techniques that some of you employ to ensure the imports in Django projects stay maintainable. I'm used to having a list of about 30 different imports in every file, and that clearly violates the DRY principle. So it's not just about aesthetics, it's also about not duplicating code.
I'm looking for a method that keeps the import sections in Django files manageable. What seems to me like a good idea is to have a generic import file for every file type (views, models, etc.), which is then imported at the top, with further application-specific imports after that. But would that cause a lot of unnecessary overhead? How should those files look, and what are the important classes for every file-type?
Update
On request, here is an example from one of my views.py
files.
from django.shortcuts import render_to_response, get_object_or_404
from shortcuts import render_to_context, render_template
from django.http import HttpResponseRedirect
from django.contrib.comments.models import Comment
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.core.urlresolvers import reverse
from models import Listing, LocationData
from django.template import RequestContext
import sys
import urllib
if sys.version_info <= (2, 5):
import simplejson as json
else:
import json
import forms
import sanitize
from models import RentListing, VacationListing, SaleListing
from django.forms.models import model_to_dict
from django.forms.formsets import formset_factory
from django.core.urlresolvers import reverse
which, as you can see, is just really messy, since I just add to the bottom of the list every time I need something in the file. Ke开发者_运维百科eping it in alphabetical order would obviously help, but there has to be a better way to generalize than what I'm doing now.
Is it worth breaking the style guideline of not using the *
import for the sake of shorter, more maintainable import sections in the actual file?
You're right that it's easy to ignore DRY when working Django imports, or with python imports in general.
It's sometimes beneficial to separate common imports by domain, then create a module for managing those imports. The next step is one of the few exceptions I make to my personal rule of "Don't use import *
"
stuff_i_always_use.py
import django.templates as templates
import tagalog.tagalog_appengine as tagalog
#etc
Then in some file:
from stuff_i_aways_use import *
You can also check how they do it at Google:
http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Imports
Tomasz already mentioned one interesting part of google's documentation concerning imports, but I think also this section is worth reading!
精彩评论