[Tutor] How do you make a module

Sean 'Shaleh' Perry shalehperry@attbi.com
Wed, 10 Apr 2002 22:21:18 -0700 (PDT)


On 11-Apr-2002 James A Roush wrote:
> I have several functions that I've written and use in multiple programs.  I
> would like to put them in a module for easier maintainability.  Could
> somebody point me to a tutorial that will explain how?
> 
> Once it's made, what directory does it go in?

you make a module every time you create a .py file.  When you want to import it
you use the filename without the '.py' extension.  So 'foo.py' becomes 'import
foo'.

If you have a directory like:

this/
     foo.py
     bar.py
     this.py

this.py could be:

#!/usr/bin/python

import foo, bar

bar.command()
x = foo.variable
print x + 2

python looks in the current directory first.  If you have a module of nifty
python code you have written and want all of your programs to use it then the
answer depends on your OS.

Under linux (bsd, unix, whatever) you can either make a ~/python directory and
add that to PYTHONPATH (see the docs for more info) or more easily just drop it
in /usr/local/lib/site-python and python should see it automatically without
further work.

My preference is to include small modules with any project that needs them and
to install bigger ones in the system directory.

Hope that helps.