Where to place imports

Duncan Booth duncan.booth at invalid.invalid
Fri Jan 23 13:50:00 EST 2009


"John [H2O]" <washakie at gmail.com> wrote:

> So it isn't inefficient to import a bunch of modules that may not be
> used, say if only one function is used that doesn't rely on a larger
> module like numpy or pylab?
> 
Not really. If you import it at all then you might as well import it on 
startup i.e. at the top of the module. Importing from inside a function 
doesn't free up the imported module when the function returns, so you 
aren't going to save any memory in the long run.

I would accept that if you have a function that may not be called in most 
runs of the program, and that function uses some large module that wouldn't 
otherwise be loaded, then you might have a case for importing it only 
inside the function. But that's a very rare situation; otherwise, just 
import it at module scope.

BTW, if you ever find you are starting to write multi-threaded applications 
then you'll really regret it if you reuse code which does imports from 
inside functions. If two or more threads try to import a module 
simultaneously then one of them might find it that not everything is 
defined in the module exists when it tries to use it.



More information about the Python-list mailing list