Beautiful Python

Chip Turner cturner at pattern.net
Mon Dec 26 13:37:51 EST 2005


On 2005-12-26 05:01:07 -0500, "Gekitsuu" <gekitsuu at gmail.com> said:

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

There is a crucial difference between Perl's 'use' and Python's 
'import' -- when they are executed.  Glossing over some details, in 
Perl, a 'use' is evaulated when a .pl or .pm file is parsed, whereas in 
Python import is executed when the statement is encountered in normal 
program flow.  One result of this is that, in Perl, this does not do 
what you expect:

if ($some_condition) {
  use SomeWierdModule;
}

What happens is that at parse time, SomeWierdModule is loaded, ignoring 
completely the if statement.  This, however, works fine in Python:

if some_condition:
  import some_weird_module

In this case, some_weird_module will only be imported if some_condition 
holds true when program flow hits the conditional.

The net result is that in Perl, putting use statements all over the 
code has no real effect, because they all get evaluated at parse time 
-- you may as well toss them prettily at the top.  In Python, though, 
there are occasional times where you *do* want to conditionally load a 
module, so it occasionally makes sense to put them in other places.  
Short of situations like the conditional importing above, though, I 
would be highly suspicious of code that gratuitously tosses imports in 
odd places; the namespace is global, after all; may as well be explicit 
upfront.

You can really see this in action with the following:

perl <<EOF
if (0) {
  use SomeWeirdModule;
}
EOF

vs

python <<EOF
if 0:
  import some_weird_module;
EOF

The perl snippet explodes on an invalid module, whereas the python 
behaves just fine.

HTH,
Chip

-- 
Chip Turner                   cturner at pattern.net




More information about the Python-list mailing list