import statement within a function

Tomasz Lisowski lisowski.tomasz at
Fri Feb 2 09:33:51 CET 2001

U¿ytkownik "Fredrik Lundh" <fredrik at> napisa³ w wiadomo¶ci
news:1Yte6.11069$AH6.1772843 at
> Tomasz Lisowski wrote:
> > I have seen often import statements included within a function's body,
> > in the global scope, as it is most common.
> > ...
> > What are the advantages of the first approach over the second. Won't
> > do the importing job many times, each time the function fun() is called?
> Depends on what you mean with "importing job" -- Python
> caches imported modules in sys.modules.  The "real" import
> is only done the first time you need a module.
> also see:
> and the language reference.

OK, I have read your mini-guide, and the language reference, and now I see,
that the penalty for executing import statement after it has been imported
for the first time is minimal. What are then advantages of importing a
module WITHIN a function. Why not place this statement in the global scope?

If a module is imported within a function, the module's name is added to the
CURRENT namespace, right. It means that other functions in the module have
no access to this module, even if it is listed in sys.modules. IMHO, this is
rather a drawback of this approach. Let me ask once more: what are the

Tomasz Lisowski

More information about the Python-list mailing list