[Tutor] Importing a module I made

Magnus Lycka magnus@thinkware.se
Mon Jan 13 10:29:01 2003


At 14:31 2003-01-13 +0000, Shey Crompton wrote:
>I have a file BankAccount_class02.py that I want to import into and use in
>another program. I have found that I can only import the file successfully
>if it is located in Python22\Lib. This is fine, but I would like to not have
>to copy every file I write, and want to import, out of my work folder
>(Python22\Python Stuff). For this to work do I have to do the PythonPath
>thing, or something similar? I'm using Win2K pro, and know how to get to the
>system\advanced\environmental variables, but I'm unsure of what to type in
>that area.

There are a few different strategies here.

First of all, I suggest that you don't put any of your own files
in Python22/Lib. If you want them in a central location, put them
in Python22/Lib/site-packages/. This directory are intended just
for these files that don't come with your standard python install.

Secondly, if the module is in the same directory as the program
that imports it runs from, imports will work fine. This is the way
most people handle their own software I think.

If you want to import your module from the Python interpreter
interactively, you can either do

 >>> import sys
 >>> sys.path.append('c:/where/ever/I/have/my/files/')

or you can do the ordinary windows dance to change the properties
of the shortcut or start menu entry you use, to start running
from your directory.

Other options are, as you suggested, to add your directory to
the PYTHONPATH environment variable. In Win2k you do this from
Control Panel -> System -> Advanced -> Environment Variables.
Just set PYTHONPATH as variable (in the upper or lower field
depending on whether you want this accessible for one particular
user or for all) and write the path to the directory as value.

Note that you need to restart your programs (Python interpreter
or whatever) for them to become aware of the environment change).

If you do work in Python/Python Stuff, you could actually do
another convenient thing. First of all. Never ever ever use
space characters in directory or file names!!! Secondly, put
your directory under site-packages instead.

Can you imagine having all the code that you write in
Python22/Lib/site-packages/PythonStuff instead of that directory
with the poor location and name ;) ?

In that case you can make that directory into a package. It's
dead simple. Just add an empty file called __init__.py !

Then you can do "import PythonStuff.BankAccount_class02"!

And while I'm whining: This isn't Java, there is no reason to
put each class in a file of its own... A file is a module, and
in Python, classes, modules (files) and packages (directories
with __init__.py) are different levels of modularization. Use
that!


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se