Geography 465 Modules and Functions Writing Custom Functions
Python Modules Each Python script is a module Modules can access other modules Modules can use variables and/or constants Modules can use functions
Writing a Function What makes a good function –Single, clear objective –Reusable by intent Function syntax –Def defines the function –Return() sends result back to calling module –See example
Syntax Example MyCustomFunction.py Def (arg1, arg2, …argN): # your custom function code return
Code example result of two numbers MyFunctions.py def calculate(num1, num2, mathOp): result = eval(str(num1) + mathOp + str(num2)) return result Interactive Window >>> import MyFunctions >>> MyFunctions.calculate (3, 4, “+”) >>> 7
Using variables in functions Assignment statement –Variables at module level are available to calling script –Variables within a function are local to the function Script1.py import NewYork nyLat = NewYork.lat nyLong = NewYork.long nyCalc = NewYork.calcgrowth ( , 0.03) Print nyCalc NewYork.py lat = # Global long = # Global def calcgrowth(pop, rate): growth = pop * rate return growth Passing values to module function
Importing a custom module First time in Python –Finds the module –Compiles the module –Runs the module Subsequent times (same Python session) –Re-uses imported (compiled) module
Finding the module Where does Python look to find module? The search path hierarchy is: –Home directory of calling module –PYTHONPATH environment variable –Standard Python library directions –Contents of.pth (text) files
Adding a custom search path Modify sys.path Append location of your custom modules Last for duration of script Resets to default when PythonWin closes Example.py import sys sys.path.append(“C:\\MyModules”) Print sys.path
Reloading a module single Python session Module load only once Script1.py NewYork.py import NewYork Access NewYork.py lat = -73 long = 40 To re-import, call reload() Interactive WindowNewYork.py >>> reload(NewYork)Access modifiedlat = NewYork.py long =
Running the module All statements execute from top to bottom –Statements do not exist until Python reaches and runs code (line by line interpret) –Code inside functions do not run until called NewYork.py lat = long = def calcgrowth (pop, rate): growth = pop * rate return growth Follow indent rules