where is best place for import statements?

John Roth newsgroups at jhrothjr.com
Thu Oct 23 14:26:47 EDT 2003


"Matthew Wilson" <mwilson at sarcastic-horse.com> wrote in message
news:slrnbpg86c.22p.mwilson at frank.homelinux.net...
> > Your cure would probably solve the problem, but I
> > consider it much worse than the disease of having
> > to remember to stick the proper import statement
> > at the front of the module. You'll get at most one
> > error in each module where you forget to do that.
> >
> > In general, importing a module at other than the
> > module level is something you do in very specialized
> > circumstances: when you need either a dynamic or
> > a conditional import.
> >
> > John Roth
>
> So, instead of scattering all those import statements throughout my
> file, I ought to just put them at the top of the file, right after the
> module description?
>
> And, if I decide to do something like
>
> from mymod import Circle
>
> Then it's up to me to remember to first do
>
> import math

At that point, it doesn't matter. It only matters when you go to
use it. However you organize the block of imports at the top
of the file will usually work; if there's a lot, I find alphabetizing
them sometimes helps, or sometimes putting the standard ones
first.

The one caveat to that is with modules that have circular
dependencies, but that's a whole different set of problems than
the one I think you're talking about.

John Roth

>
> Is that right?
>
>






More information about the Python-list mailing list