import statement within a function

Tomasz Lisowski lisowski.tomasz at sssa.NOSPAM.com.pl
Fri Feb 2 09:33:51 CET 2001


U¿ytkownik "Fredrik Lundh" <fredrik at effbot.org> napisa³ w wiadomo¶ci
news:1Yte6.11069$AH6.1772843 at newsc.telia.net...
> Tomasz Lisowski wrote:
> > I have seen often import statements included within a function's body,
not
> > in the global scope, as it is most common.
> > ...
> > What are the advantages of the first approach over the second. Won't
Python
> > 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:
> http://effbot.org/guides/import-confusion.htm
> 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
advantages?

Tomasz Lisowski






More information about the Python-list mailing list