Python Functions


Functions (any kind related to programming) is a way to reuse and make coding more efficient. Functions allow for fewer lines of code and provide a means to access the same set of code for similar and possibly repetitive tasks with the same (arguments) parameters. An argument is a value (can be any kind of represented value such as a feature class, image, table, text string, number, data path (which is a string), etc). Arguments provide the specific information needed for the function to process the lines of code within the function. Often functions can contain many lines of code, while some may only have a couple of lines to perform simple tasks.

As a simple example, if a coder finds that a simple math problem (algorithm) needs to be computed at different points in the script, instead of rewriting or copy/pasting the same set of lines of code, the few lines of code can be placed in a function and then have the function “called” to perform the math problem. The function can return the result and the result can even be used in subsequent lines of code.

I consider writing functions as a “phase 2” in code writing because oftentimes the coder doesn’t realize that a function could be used until after an initial draft of code has been written and thoroughly tested. There is no requirement for a “phase 2” writing and using functions, but for the unseasoned coder, this realization may not be noticed until an entire script (or portion of a script) is written and evaluated for potential code writing improvements.

See the Chapter 10\Python_v3_Scripts_ProPackage folder in the file to see an example of a complete script using a Python function.

Structure of a Function

A function is defined (in Python) toward the top of a script and uses the “def” keyword to define the section (lines of code) as a self-contained set of code that focuses on a limited set of processes that is likely “called” (aka accessed) multiple times when the script is processed. Scripts can have many functions and functions can be quite lengthy. The following shows the general script layout for constructing and using a Python function.

import arcpy, os, sys, traceback # plus any other Python modules needed

# function definition
def aFunction(<optional parameters>):
    #indented body of the function
    return # aValue - the return can be optional

#often variable definitions go here
    # main body of script
    # function call (right side of equal sign; arguments in parentheses are optional)
    # function return value (if needed, left side of the equal sign)

    # example
    returnValue = aFunction(x)
   # other lines of code

    #except code goes here

Function without a Return Value

This snippet shows only the function definition that does not have a return value. Assume that values (arguments, aNumber and anotherNumber) being passed to the PrintThis function have been defined in a “main” part of an existing script.

def PrintThis (aNumber, anotherNumber):

        print  ("The print function prints: " + \ 
             str(aNumber) +  " and " + str(anotherNumber))

Function with a Return Value

This snippet shows only the function definition that does have a return value. Assume that the value (argument, anInteger has been defined in a “main” part of an existing script. Note the return keyword provides for the variable, resultValue to be passed back to the “main” part of the script.

def CalcValue(anInteger):
    resultValue = anInteger + 1
    return resultValue

A Simple Function Example

Notice in this simple example after the import line, the function definition is defined.

After this set of code, the main body of the Python function is written.

Within the try block contains the script lines to process. The general order of the steps to process the lines of code that include a function are:

  1. When the resultValue = CalcValue(x) is processed, the right side of the equal sign calls the CalcValue function and includes the single parameter (represented by x).
  2. The CalcValue function is processed (i.e. the line beginning with def CalcValue(anInteger):).
  3. Since the keyword “return” is used in the function, the value of resultValue is returned to the main body of the script at the same line of code showing resultValue on the left side of the equal sign.
  4. The script continues process with the print statement. In this case, the value returned from the function is printed to the Python Shell.
import arcpy, os, sys, traceback
# function definition
# Step 2
def CalcValue(anInteger):
    resultValue = anInteger + 1
    # Step 3
    return resultValue
    print ("Computing a value...")
    x = 0
    print ("Start value is: " + str(x))
    # function call, passing an argument (in this case the value of x, which is 0)
    # and accepting a returned value
    # Step 1 (right side of the equal sign.  The value 0 is passed to the CalcValue function)
    # Step 3 (left side of the equal sign.  The returned value from the function is 1 (i.e 0 + 1))
    returnedValue = CalcValue(x)
    # Step 4 - the returned value is used in a subsequent line of code
    print ("Returned Value is: " + str(returnedValue))

    # except shown here for context