Best practices with import?

Peter Hansen peter at engcorp.com
Sun Jul 29 01:07:57 EDT 2001


Tom Bryan wrote:
> 
> Alex wrote:
> 
> > Goodness, without import, python's close to useless.
> 
> Well, of course.  But where to import?  What's the most common idiom?

At the top, unless you have a specific need to import in a
function.

Possible reasons to import in a function: 

 1. Readability: if the import is needed in only one
    function and that's very unlikely ever to change,
    it might be clearer and cleaner to put it there only.

 2. Startup time: if you don't have the import outside
    of the function definitions, it will not execute
    when your module is first imported by another, but
    only when one of the functions is called.  This
    delays the overhead of the import (or avoids it
    if the functions might never be called).

 3. There is always one more reason than the ones
    we've thought of until now.

> import sys, os, string
> 
> or
> 
> import sys
> import os
> import string

The first for very small simple files, as a matter of 
personal preference.

The latter for larger files in applications expected to have
more frequent maintenance.  It is less error-prone for a
programmer to remove an entire line like 'import os' than
it is for her to go in and delete "os, " from in the middle
of the other line.  It also allows one to add comments after
each line, explaining something about the need for the 
import (e.g. "import os     # need popen() to call other apps").

> > I'm not sure what advantage there might be to deleting module references
> > in a function's scope just prior to leaving it.  I would have thought
> > the reference was usually dropped at that point, anyway.
> 
> After digging at Google Groups, I think that it might have been a comment
> about importing and then deleting at the module level.  At least, I see
> that the timbot is still explaining why threading.py does this.
> 
> import sys
> import time
> 
> # Rename some stuff so "from threading import *" is safe
> 
> _sys = sys
> del sys
> 
> _time = time.time
> _sleep = time.sleep
> del time

Never do this. :)

At least, don't bother thinking about doing it until you can figure
out why it's needed, because you shouldn't be making it easier for
someone to do "from yourmodule import *" unless you have very good
reason.

(By the way, most of the answers to your questions are a matter
of personal preference, or local coding convention, which might
be why you haven't seen more explicit discussions before.)

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list