Beautiful Python

sconce at in-spec-inc.com sconce at in-spec-inc.com
Mon Dec 26 16:32:40 EST 2005


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.

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".




More information about the Python-list mailing list