Best practices with import?

Gordon McMillan gmcm at hypernet.com
Sun Jul 29 09:11:57 EDT 2001


Peter Hansen wrote: 

[snip]

> There is at least one situation where import in a function is very
> useful, and that is to delay execution of the import.  If the first
> module is imported by another, and all of its import statements are
> at the top, each import executes at that time, slowing down loading
> of the first module.  If one of the imported modules is needed only
> in one of the functions, which may or may not be called, putting 
> the import statement in the function will postpone (perhaps avoid)
> the import and improve responsiveness.
 
It's also very useful in some circular import situations.

Circular imports are fine where both modules use the "import <module>"
form of import. They fail when the 2nd module wants to grab a name
out of the first ("from module import name") and the import is at
the top level. That's because names in the 1st are not yet available,
(the first module is busy importing the 2nd).

As above, this is a sensible solution only if the use of the imported
module is confined to the one function.

- Gordon




More information about the Python-list mailing list