Using functions in Python

A function is a defined bit of functionality that does a specific task and can be incorporated into a larger program.

In ArcPy, all geoprocessing tools are provided as functions, but not all functions are geoprocessing tools. In addition to tools, ArcPy provides a number of functions to better support geoprocessing workflows using Python. Functions can be used to list certain datasets, retrieve a dataset's properties, validate a table name before adding it to a geodatabase, or perform many other useful geoprocessing tasks. These functions are available only from ArcPy and not as tools in ArcGIS applications, since they are designed for Python workflows.

The general form of a function is similar to that of tool; it takes arguments, which may or may not be required, and returns something. The returned value of a nontool function can be varied—anything from strings to geoprocessing objects. Tool functions will always return a Result object and provide geoprocessing messages support.

The following example uses two ArcPy functions, GetParameterAsText to receive an input argument, and Exists to determine whether or not the input exists. The Exists function returns a Boolean value (either True or False).

import arcpy

input = arcpy.GetParameterAsText(0)
if arcpy.Exists(input):
    print("Data exists")
else: 
    print("Data does not exist")

The following example creates a list of feature classes using the ListFeatureClasses function, and then loops through the list, clipping each individual feature class with a boundary feature class.


import arcpy
import os

# The workspace environment needs to be set before ListFeatureClasses
#    to identify which workspace the list will be based on
#   
arcpy.env.workspace = "c:/data"
out_workspace = "c:/data/results/"
clip_features = "c:/data/testarea/boundary.shp"

# Loop through a list of feature classes in the workspace
#
for fc in arcpy.ListFeatureClasses():
    # Set the output name to be the same as the input name, and 
    #    locate in the 'out_workspace' workspace
    #
    output = os.path.join(out_workspace, fc)

    # Clip each input feature class in the list
    #
    arcpy.Clip_analysis(fc, clip_features, output, 0.1)

Related topics