where is best place for import statements?

Peter Otten __peter__ at web.de
Thu Oct 23 15:27:37 EDT 2003


Matthew Wilson wrote:

> 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

Literal answer: put

from math import *

into myshapes.py, and access variables and functions like so:
#test1.py
import myshapes
myshapes.pi
myshapes.sin(alpha)
myshapes.whatever
...
#end test1.py

However, I've got the impression that you think that in order to *use* your
myshapes module, you have to import the math module.

That is wrong, e. g.:

#myshapes.py
import math
class Circle:
    def __init__(self, x, y, r):
        self.circumference = 2*r*math.pi 
#end myshapes py>

You can use this in a script that does *not* import math:

#test.py
import myshapes
veryRoundCircle = Circle(0, 0, 1.0)
print veryRoundCircle.circumference
#end test.py

The general idea is to design modules as orthogonal as possible, i. e. it is
good design for a module to provide its functionality without imposing
restrictions on the client code. The usage of math.pi is only an
implementation detail, that the user of myshape should not have to bother
about. If you later add a Rectangle, you could provide a, say, turn(angle)
method, again with the effect of *eliminating* the need for math.sin() etc.
in client code. 

As an aside, think about making circumference in the above example a method,
if you also store the radius in the instance. If you later change the
radius, the circumference is thus updated automatically. General rule:
avoid redundant data.

Peter






More information about the Python-list mailing list