[TriLUG] making a python module
bcpowell at email.unc.edu
bcpowell at email.unc.edu
Sat Feb 9 20:58:06 EST 2008
The python idiom for this is to condition your execution on the value
of the __name__ variable. This is set to the module name if the file
has been imported as a module, and has the special value "__main__" if
the file is being run as a script by the python interpreter. So you can
put your test code inside a 'if __name__ == "__main__":' block. For
instance:
#!/usr/bin/python
#volume_sphere.py
import math
def volume_sphere(r):
return 4 * math.pi * r * r / 3
if __name__ == '__main__':
print volume_sphere(2)
(the following message snipped for length):
Quoting Joseph Mack NA3T <jmack at wm7d.net>:
> I'm a python newbie
>
> I've got a simple python program with a function and code
> (main?) that does test calls.
>
>
> What I was hoping to do was to leave the calls in the
> original volume_sphere.py (which became volume.py) as test
> cases, so that anyone could test the module without having
> to write a special piece of calling code.
>
> I find that if I leave the test calls in main in the module
> file, that these are executed too when I call the function
> from demo_volume_sphere. I don't understand why the code in
> main() is executed since I called the function, not the
> whole file.
>
> I've looked around with google to see how modules are made,
> but none of the modules have a test main() in them.
>
> Anyone know how to do what I'm trying to do?
>
More information about the TriLUG
mailing list