import statement within a function

Fredrik Lundh fredrik at effbot.org
Fri Feb 2 04:40:39 EST 2001


Tomasz Lisowski wrote:
> 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.

- lazy importing: if you place it within a function, the module
is only imported if your program really needs it.

- import dependencies (see the recursive import section in the
mini-guide).  if you use from-import on the module level, you
can end up in situations where the things you import doesn't
yet exist.

- performance: local lookup is faster than global lookup.

- readability: it can be easier to grok your code if you import
things (i.e. define names) near the place you're using them.

(etc)

Cheers /F





More information about the Python-list mailing list