import statement within a function

Tomasz Lisowski lisowski.tomasz at sssa.NOSPAM.com.pl
Sat Feb 3 02:43:47 EST 2001


Uzytkownik "Peter Hansen" <peter at engcorp.com> napisal w wiadomosci
news:3A7AB654.D6C16746 at engcorp.com...
<.>
> > > - 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.

That depends, on what the given function does, and how often it is called,
of course.

> 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).

I dare to disagree with you, as I find it very convenient to find all import
statements at the beginning of the source file, without having to scan the
file, if there are any other modules, that I have requested. Perhaps my
opinion is influenced by my Delphi programming habits, where I could find
all modules imported in the 'uses' clause, easily locateable in the source
file.

Moreover, it is a matter of taste, whether I put the import statement at the
beginning of the file, even if the given module is imported only by one
function, since this function will be eventually called (there was surely a
reason for writing it, wasn't it?). Therefore I have asked Frederik about
REAL advantages, that could persuade me to put import statements within a
function. Performance, IMHO, is one of them.

Tomasz Lisowski





More information about the Python-list mailing list