Structuring Programs with Modules (Files)
Introduction
We've already begun structuring our programs by creating "functions". We can now put functions into separate files called "modules" and then we can reuse them from multiple other Python scripts. This allows you to just write a function once and then use it over and over again. This not only reduces the amount of code you have to write and support but over time the quality of the code will increase because you are regularly testing the same functions, fixing defects in them, and then using them in new ways.
A Module for Unit Conversion
In GIS, we are often converting from miles to meters, meters to kilometers, and so on. A useful module is one that takes care of unit conversions. Enter the code below in a new file and save it as "UnitConversion.py":
METERS_PER_MILE=1609.344 def MilesToMeters(Miles): Meters=METERS_PER_MILE*Miles return(Meters) def MetersToMiles(Meters): Miles=Meters/METERS_PER_MILE return(Meters)
Note: There is an error in this code but don't fix it yet!
The first line of the file just defines the number meters in a mile. The next function will convert measurements in miles to meters and the second function converts meters to miles. These are pretty easy functions and we could type in the conversion every time, but the chance that we will make errors is pretty high. Putting the code into a function makes it so we don't have to lookup the conversion each time and reduces the chance that we'll make a mistake. As the functions become larger, the value of modules will increase rapidly.
Now create a new file, enter the code below, and save it as "UnitConversionTest.py". I always create a test file for each module both so I can make sure it works and if I think there are problems in the future, I can just run the test file to see if something has gone wrong.
import UnitConversion Meters=UnitConversion.MilesToMeters(1) print("Should return about 1609: "+format(Meters)) Miles=UnitConversion.MetersToMiles(1000) print("Should return about 0.62137: "+format(Miles))
Run the script and see if the values are correct. If you have problems, you can use the "step into" function with a breakpoint to step into the module as it executes.
Notes: It may become confusing which file you are running while working in an IDE (like Wing). When you edit the module, make sure you save it and then return to the main script before hitting run. Otherwise, the module may not be saved or you may try running the module which will not produce any output.