Where to put the import command in the file?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Oct 3 07:31:44 CEST 2007

En Tue, 02 Oct 2007 19:01:27 -0300, wang frank <fw3 at hotmail.co.jp>  

> I am writing Python script now. The project will grow bigger in future.  
> I need to import some packages for several functions, such as numpy.  
> Where is the best plalce to put the import numpy command? Is it fine to  
> put on the first line in the file?

Yes, this is the usual way.

> Is it better to put it into each function after the def functionname? or  
> they are the same.

I only place an import inside a function when it's expensive (e.g. loads a  
lot of things) and not always required, or when it's irrelevant to the  
main purpose of the module (e.g. "import traceback" when it's used just to  
handle some special exceptions).

> Since numpy function will be used in all files, so I have to import it  
> in each files. Does this will increase the memory usuage or there are  
> better way to do it.

No. Only the first import actually has to load the module; later imports  
quickly return a reference to the already loaded module.

Gabriel Genellina

More information about the Python-list mailing list