import statement within a function

Peter Hansen peter at
Fri Feb 2 08:29:56 EST 2001

Tomasz Lisowski wrote:
> "Fredrik Lundh" <fredrik at>:
> > Tomasz Lisowski wrote:
> > > 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.
>  Yes, that's really a good point!
> > - readability: it can be easier to grok your code if you import
> > things (i.e. define names) near the place you're using them.
> Thanks, Frederik, that is really a good explanation! BTW, I really
> appreciate your "Introduction to Tkinter". I am using it alot.

The one you highlight, "performance", should probably be
considered the _least_ important of the points Fredrik raised.

The last one, which implies improved maintainability, is
far more important (IMHO), and that alone is a good reason
to put import within a function instead of 'without'
(provided the imported module is not needed throughout
the importing module of course).

More information about the Python-list mailing list