Beautiful Python

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Dec 26 09:08:01 EST 2005


On Mon, 26 Dec 2005 02:01:07 -0800, Gekitsuu wrote:

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

Maintainability is a good reason for doing imports at the beginning of
your module. But it isn't the only consideration:

- if your module only imports modules which are part of the standard
library, the maintainability argument is irrelevant (except possibly for
very special cases like "I want to back-port your module to Python 1.5,
what modules do I need?").

- Encapsulation: sometimes you want to import objects so they are local to
a function or class. If you import them at the beginning of the module,
they will be global to the module.

- Cost: importing a module may not be cheap. Why pay that cost if you
don't need to? Sometimes it makes sense to delay importing until you
know you really need it.

- Namespace pollution: when a module imports your module, it will see
everything you have imported. By delaying imports to a local scope, you
reduce the number of objects in your module namespace that get exported.

These arguments are especially strong when using the "from module import
name" form of import.

Putting all your imports together at the beginning is recommended
but not compulsory precisely because there can be good reasons for
delaying imports. Think of "always do your imports at the beginning" as a
guideline, not a law. If you are writing something like:

import A
...code...
import B
...code...
import C
...code...

then this should be re-written as:

import A
import B
import C  # or just import A, B, C
...code...

But if you are writing:

import A
...code...
def foo():
    import B
    # module B is only used in foo
    ...code...

then I don't think there is anything necessarily wrong with that. 


-- 
Steven.




More information about the Python-list mailing list