where is best place for import statements?

John Roth newsgroups at jhrothjr.com
Thu Oct 23 12:03:56 EDT 2003


"Matthew Wilson" <mwilson at sarcastic-horse.com> wrote in message
news:slrnbpfsa1.200.mwilson at frank.homelinux.net...
> Hi-
>
>
> I'm writing a bunch of classes, several of which need functions and
> variables defined in the math module.  In some instances, I'm going to
> import my module like this:
>
> import myshapes
>
> and then in others, I'll do:
>
> from myshapes import Circle
>
> or even:
>
> from myshapes import *
>
> How do I make sure that no matter how I import stuff from myshapes.py, I
> always also import the math module?  Should I write all of my functions
> like so:
>
> def foo1():
>     import math
>     return math.pi
>
> def foo2():
>     import math
>     return 2*math.pi
>
> and all my classes like this:
>
> class Circle:
>     def __init__(self,x, y, r):
>         import math
>         self.circumference = 2*r*math.pi
>
> Is this the way to solve the problem?

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


>
> Thanks for the help.






More information about the Python-list mailing list