July 22, 2024

Python micromount database -- files and modules

Up to now I have simply made sure that every python program I write is contained in one and only one source file. But I would like to organize this project in a better way, using multiple files.

Python has a very mature and well understood "module" scheme to support this sort of thing. What I have always worried about is how I can install a program composed of a collection of files and still have it find all of its components.

It turns out I have worried too much. In every experiment I have performed, it just works and does the right thing. Certainly it works when you invoke the program in the directory that contains all the pieces. But you can also invoke it via "path/to/program.py" and it knows to find all the pieces in the same directory that contains the "main" program. And, to my amazement, you can create a symbolic link to the program and it all just works. In other words you can do this:

cd /home/tom/bin
ln -s /xyz/database/micros.py micros
cd
micros
This answers all my questions about where files ought to go, now it is just a matter of improving my knowledge of python modules.

Python modules - an executive course

Put stuff into a file junk.py -- then in the "main" file do this:
import junk
Once you do this, all the functions and variables in junk.py are available, but with "junk" as a prefix, i.e. a method will need to be called as junk.sub().

Some other variations of this are:

from junk import a, b, c
import junk as JJ
from junk import aardvaark as av
from junk import *
The last of these is deprecated, but certainly works if you are happy with the unpredictability of pulling who knows what into your current namespace.
Feedback? Questions? Drop me a line!

Tom's Mineralogy Info / [email protected]