[Tutor] question about where to import [import caches modules]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 3 Apr 2002 12:28:43 -0800 (PST)


On Mon, 1 Apr 2002, Erik Price wrote:

> I have a quick question about where import statements should go.  Most
> scripts feature them at the top of the script, or module, or whatever

I usually look for import statements near the top of my source files.



> definitions.  Is there some reason that the author would choose to put
> their import statement in a method definition?  I am probably wrong, but
> doesn't that mean that these modules are imported every time the method
> is called?

Thankfully, no.  Python keeps a cached list of loaded modules in memory,
so that the next time a module is 'import'ed, it ends up being a "no-op",
that is, it becomes an operation that Python just ignores.

By the way, this caching behavior is the reason why we have the reload()
function, to convince Python to toss out the cached module and really try
importing a module from scratch.