[Tutor] general import VS importing inside a function

Kent Johnson kent37 at tds.net
Sat Aug 29 12:38:26 CEST 2009


On Fri, Aug 28, 2009 at 10:34 PM, Fidel
Sanchez-Bueno<fidellira.6 at gmail.com> wrote:
> What is the best aproach when it comes to import??, is allways better to
> make all the import calls in the global scope, making the overall runtime of
> the program better because the program is not going to import something
> everytime a function is called, or is better to make specific import's
> inside a function making the function completely portable??

Imports are conventionally put at the start of a module. Generally the
unit of reuse in Python is a module, not a function, so you don't
limit portability by putting the imports at the top of a module.

>  and another thing, making specific import, makes the program less, how you
> said this "RAM eater" (sorry my native language is spanish and i dont now
> how to translate "cosume menos recursos" google says "cosumes less
> resources", but anyway i hope you get it)

Modules are only loaded once, at the first import. The loaded modules
are cached in sys.modules. So subsequent imports are fast (just a
dictionary lookup) and don't consume any resources.

> I say this because, for example when i'm in the interactive shell and import
> big things like Scipy, and NumPy, python takes 3 to 5 seconds to respond,
> and if am only going to use like 4 or 5 function inside NumPy i think is
> better to say just "from Numpy import foo, bar, qux etc" but i would
> actually like to read this from someone that knows about programming and not
> just me making asumptions...

It will take the same amount of time for the import with either style
of import. It is the initial load of the module that takes time and
memory.

Kent


More information about the Tutor mailing list