Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep imports neat in Django?

Tags:

python

django

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. Keeping 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?

like image 532
Herman Schaaf Avatar asked Jan 21 '11 20:01

Herman Schaaf


1 Answers

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 *
like image 162
Kyle Wild Avatar answered Sep 20 '22 06:09

Kyle Wild