Im torn between two general module import styles. The import-everything-at-the-top approach where the beginning of each python file/module imports every module potentially needed later in the file OR the import-as-needed approach.
I know what I dont like; a file starting w/ 20+ import lines, that just seems ugly and java-y (no-flame, just sayin) to me. OTOH, the as-needed-approach seems perhaps a little too, uhm, disorganized? Although Id guess Im probably more partial to that approach.
This is a pretty minor stylistic issue but I havent settled on one approach and I'd like some feedback to come to some conclusion once and for all.
For example,
import foo
import baz
import bar
import quux
import django.foo
# etc
vs.
import sys
def some_os_thing():
import os
print os.getcwd()
def some_http_thing():
import urllib
print urllib.urlopen('http://...').read()
While technically Python doesn't import anything twice, it still takes nonzero time to check the module registry (a dictionary lookup). So if this happens every time your functions are called, it's unnecessary work, even if it's fast.
I personally tend to do all imports in one place, with the exception of test routines: I figure that a user of a module shouldn't really "depend" on modules that are only needed in test mode, so e.g. I would do a local "import" inside a _test() function.