Best practices with import?
Just van Rossum
just at letterror.com
Sun Jul 29 03:43:27 EDT 2001
Peter Hansen wrote:
>
> Tom Bryan wrote:
> >
> > Alex wrote:
> >
> > > Goodness, without import, python's close to useless.
> >
> > Well, of course. But where to import? What's the most common idiom?
>
> At the top, unless you have a specific need to import in a
> function.
>
> Possible reasons to import in a function:
>
> 1. Readability: if the import is needed in only one
> function and that's very unlikely ever to change,
> it might be clearer and cleaner to put it there only.
>
> 2. Startup time: if you don't have the import outside
> of the function definitions, it will not execute
> when your module is first imported by another, but
> only when one of the functions is called. This
> delays the overhead of the import (or avoids it
> if the functions might never be called).
>
> 3. There is always one more reason than the ones
> we've thought of until now.
I know one more:
4. Overhead: if the module imports a lot of modules,
and there's a good chance only a few will actually
be used. This is similar to the "Startup time"
reason, but goes a little further. If a script
using your module only uses a small subset of the
functionality it can save quite some time, especially
if the imports that can be avoided also import a lot
of modules.
Just
More information about the Python-list
mailing list