[EMAIL PROTECTED] wrote: > Gekitsuu wrote: >> I've been reading a lot of python modules lately to see how they work >> and I've stumbled across something that's sort of annoying and wanted >> to find out of there was a good reason behind it. In a Perl program >> when you're calling other modules you'll add "use" statements at the >> beginning of your script like: >> >> use strict; >> use WWW::Mechanize; >> use CGI; >> >> This seems to be the de facto standard in the Perl community but in >> python it seems most of the code I look at has import statements >> everywhere in the code. Is there a sound reason for putting the imports >> there are are developers just loading modules in as they need them. I >> own Damian Conway's book of Perl Best Practices and it seems from a >> maintainability standpoint that having all the modules declared at the >> beginning would make it easier for someone coming behind you to see >> what other modules they need to use yours. Being new I didn't know if >> there was a performance reason for doing this or it is simply a common >> habit of developers. > > > Without taking anything away from other posts responding to your > question, the first response perhaps should have been: > > "Imports are always put at the top of the file, just after > any module comments and docstrings, and before module > globals and constants." > > Which is the "official" Python style guide, PEP 0008, at > http://www.python.org/peps/pep-0008.html > and basically a reflection of Guido's own recommendations.
I've always done it this way (import at the top in alphabetical order with standard modules before add-in modules). The one exception is that at times I use imports to make sure that certain modules are indeed installed. For example, when I must have win32 modules I import like this: import os import sys import time try: import win32api except ImportError: print "The win32 extensions must be installed!" sys.exit() > > There are reasons to break almost any rule sometimes(*), but I think > you were asking whether there IS a rule -- which is an insightful, > worthy question if you've been looking at code which begs it. > > -Bill > > > (*) PEP 0008 itself says, even before it lays out any rules, > "know when to be inconsistent". > -- http://mail.python.org/mailman/listinfo/python-list