[TriLUG] making a python module

Michael Hrivnak mhrivnak at hrivnak.org
Sat Feb 9 13:13:56 EST 2008


Quick point: what you are calling "main()" looks to just be the global 
namespace.  When importing from a file, things in the global namespace get 
executed.

I'm not sure what you mean by wanting people to test your function without 
writing calling code.  Maybe this would suffice:

-----------
#!/usr/bin/python
#volume_sphere.py
def volume_sphere(r):
	do_magic_stuff(r)
	return volume_sphere
----------

----------
tester at hisorhermachine:~$ python -i volume_sphere.py
>>> volume_sphere(4)
268.0825731063467
>>>
tester at hisorhermachine:~$
---------

The tester still has to call the function, but nothing more.  Or, you could 
simply write a small program that takes input from the user and calls 
volume_sphere().

Michael


On Saturday 09 February 2008 10:20:42 am Joseph Mack NA3T wrote:
> I'm a python newbie
>
> I've got a simple python program with a function and code
> (main?) that does test calls.
>
>
> #!/usr/bin/python
> #volume_sphere.py
> def volume_sphere(r):
> .
> .
>  	return volume_sphere
>
> #main()
> print volume_sphere(2)
> #---
>
> all fine and dandy. I can make it into a module by
> commenting out the call in main() and copying the file into
> volume.py and calling the function from the following code.
>
> #! /usr/bin/python
> #demo_volume_sphere.py
> from volume import volume_sphere
>
> print volume_sphere(1)
> print volume_sphere("-1")
> #---
>
> again all fine and dandy.
>
> 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?
>
> Thanks Joe
>
> --
> Joseph Mack NA3T EME(B,D), FM05lw North Carolina
> jmack (at) wm7d (dot) net - azimuthal equidistant map
> generator at http://www.wm7d.net/azproj.shtml
> Homepage http://www.austintek.com/ It's GNU/Linux!


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://www.trilug.org/pipermail/trilug/attachments/20080209/8d4de544/attachment.pgp>


More information about the TriLUG mailing list