Customizing script tool behavior

Validation is everything that happens before clicking the tool's OK button. When creating your own custom tools, validation allows you to customize how parameters respond and interact with values and each other. Validation is performed with a block of Python code that is used to control tool behavior.

To learn more about validation, see Understanding validation in script tools.

You can provide custom behavior for your script tool dialog box, such as enabling and disabling parameters, providing default values, and updating string keywords. To add custom behavior for your script tool, right-click the script tool, click Properties, and click the Validation tab. In the Validation panel, you can provide Python code that implements a Python class named ToolValidator.

ToolValidator is a Python class that contains four methods: initializeParameters, isLicensed, updateParameters, and updateMessages. It also contains the standard Python class initialization method, __init__. To view and edit the ToolValidator class, right-click your script tool, click Properties, and click Validation. The code sample below shows the default ToolValidator class code. The Python code can be edited in place, or alternatively, click the Open in Script Editor button to edit the code.

Default ToolValidator class and methods
import arcpy

class ToolValidator(object):
    """Class for validating a tool's parameter values and controlling
    the behavior of the tool's dialog."""

    def __init__(self):
        """Setup arcpy and the list of tool parameters.""" 
        self.params = arcpy.GetParameterInfo()

    def initializeParameters(self): 
        """Refine the properties of a tool's parameters. This method is 
        called when the tool is opened."""

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self):
        """Modify the values and properties of parameters before internal
        validation is performed. This method is called whenever a parameter
        has been changed."""

    def updateMessages(self):
        """Modify the messages created by internal validation for each tool
        parameter. This method is called after internal validation."""

MethodDescription

__init__

Initializes the ToolValidator class. Import any libraries you need and initialize the object (self).

initializeParameters

Refines the properties of a tool's parameters. Called once when the tool dialog box first opens or when the tool is executed from Python.

isLicensed

Sets whether a tool is licensed to execute. Called once when the tool dialog box first opens or when the tool is executed from Python.

updateParameters

Called each time the user changes a parameter on the tool dialog box. After returning from updateParameters, geoprocessing calls its internal validation routine.

updateMessages

Called after returning from the internal validation routine. You can examine the messages created from internal validation and change them if desired.

ToolValidator methods overview
Nota:

Avoid using time-consuming tasks such as geoprocessing tools or the opening of datasets in your validation code, as the ToolValidator class is executed each time a change is made in the tool dialog box. Use geoprocessing tools in your script—not in ToolValidator.

Following are some examples of ToolValidator code. For a description of all the methods and more examples, see Programming a ToolValidator class.

To enable or disable a parameter

This example is from the Hot Spot Analysis tool:

def updateParameters(self):
    # If the option to use a weights file is selected (the user chose
    #  "Get Spatial Weights From File"), enable the parameter for specifying 
    #  the file, otherwise disable it
    #
    if self.params[3].value == "Get Spatial Weights From File":
        self.params[8].enabled = True
    else:
        self.params[8].enabled = False

To set a default value

This example is also from the Hot Spot Analysis tool:

def updateParameters(self):
    # Set the default distance threshold to 1/100 of the larger of the width
    #  or height of the extent of the input features.  Do not set if there is no 
    #  input dataset yet, or the user has set a specific distance (Altered is true).

    if self.params[0].valueAsText:
        if not self.params[6].altered:
            extent = arcpy.Describe(self.params[0]).extent
            if extent.width > extent.height:
                self.params[6].value = extent.width / 100
            else:
                self.params[6].value = extent.height / 100

    return

To update a filter

Following is an example of dynamically updating a Value List Filter containing a choice list of keywords. If the user enters OLD_FORMAT in the second parameter, the third parameter contains POINT, LINE, and POLYGON. If NEW_FORMAT is entered, the third parameter contains three additional choices.

import arcpy

class ToolValidator:
    def __init__(self): 
        self.params = arcpy.GetParameterInfo()

    def initializeParameters(self):
        return

    def updateParameters(self):
        # Provide default values for "file format type" and 
        #  "feature type in file"
        #
        if not self.params[1].altered:
            self.params[1].value = "OLD_FORMAT"
        if not self.params[2].altered:
            self.params[2].value = "POINT"

        # Update the value list filter of the "feature type in file" parameter 
        #   depending on the type of file (old vs. new format) input
        #
        if self.params[1].value == "OLD_FORMAT":
            self.params[2].filter.list = ["POINT", "LINE", "POLYGON"]
        elif self.params[1].value == "NEW_FORMAT":
            self.params[2].filter.list = ["POINT", "LINE", "POLYGON",
                                          "POINT_WITH_ANNO",
                                          "LINE_WITH_ANNO",
                                          "POLYGON_WITH_ANNO"]

        return

    def updateMessages(self):
        return

Here is another example in which the Value List Filter in the second parameter changes based on the shape type found in the first parameter, a feature class:

def updateParameters(self):
    # Update the value list filter in the second parameter based on the 
    #   shape type in the first parameter
    #
    stringFilter = self.params[1].filter

    if self.params[0].valueAsText:
        shapetype = arcpy.Describe(self.params[0]).shapeType.lower()
        if shapetype == "point" or shapetype == "multipoint":
            stringFilter.list = ["RED", "GREEN", "BLUE"]
        elif shapetype == "polygon":
            stringFilter.list = ["WHITE", "GRAY", "BLACK"]
        else:
            stringFilter.list = ["ORANGE", "INDIGO", "VIOLET"]
    else:
        stringFilter.list = ["RED", "GREEN", "BLUE"]

    # If the user hasn't changed the keyword value, set it to the default value
    #  (first value in the value list filter).
    #
    if not self.params[1].altered:
        self.params[1].value = stringFilter.list[0]
        
    return

To customize a message

def updateMessages(self):
    self.params[6].clearMessage()

    # Check to see if the threshold distance contains a value of zero and the user has
    #  specified a fixed distance band.
    #
    if self.params[6].value <= 0:
        if self.params[3].value == "Fixed Distance Band":
            self.params[6].setErrorMessage("Zero or a negative distance is invalid \
                                            when using a fixed distance band. Please \
                                            use a positive value greater than zero." )
    elif self.params[6].value < 0:
        self.params[6].setErrorMessage("A positive distance value is required \
                                        when using a fixed distance band. \
                                        Please specify a distance.")

    return

Updating the description of output data using the Schema object

In addition to customizing the behavior of the tool dialog box, you can use tool validation to update descriptions of output data variables for ModelBuilder. You can think of data variables in ModelBuilder as nothing more than brief descriptions of datasets. Data variables contain description of data on disk, including information such as the name, fields, extent, and other data characteristics that can be described using the Describe function.

All tools should update the description of their output data for use in ModelBuilder. By updating the description, subsequent processes in ModelBuilder can see pending changes to data before any process is run. The two examples below show how subsequent processes see pending changes.

For example, when the Add Field tool is used in ModelBuilder, its output data variable is updated to include the new field so that subsequent tools that depend on recognizing the field name (such as Calculate Field) can see the intended field name and use it for parameters that require it.

In the ToolValidator class, you can use a Schema object to set rules for building the description of the output; for example, you can set rules such as the following:

  • Make a copy of the input dataset description and add a new field to its list of fields (such as Add Field), or add a list of fixed fields (such as Add XY Coordinates).
  • Set the list of output fields to be all the fields in a collection of datasets and, optionally, add fields to contain the feature IDs from the collection of datasets (such as Union and Intersect).
  • Set the extent to that of a dataset in another parameter, or the union or intersection (such as Clip) of datasets in a list of parameters.
  • Set a specific geometry type (point, line, polygon), or set it to that of a dataset in another parameter or to the minimum or maximum type in a list of parameters. The definition of minimum and maximum geometry type is points = 0, polylines = 1, polygons = 2, so the minimum geometry type in the set {point, polyline, polygon} is point, and the maximum is polygon.

Output parameters have a schema

The Schema object is created for you by geoprocessing. Every output parameter of type feature class, table, raster, or workspace has a Schema object. Only feature class, table, raster, and workspace output data types have a schema—other data types do not. You access this schema through the Parameter object and set the rules for describing the output. On return from updateParameters, the internal validation routine examines the rules you set and updates the description of the output.

Setting dependencies

Whenever you create a rule, such as copy the fields of the dataset in parameter 3 and add a field, you must tell the Schema object from what parameter you want to copy (parameter 3). This is done by adding dependencies to the Parameter object. You can add more than one dependency.

def initializeParameters(self):
    # Set the dependencies for the output and its schema properties
    #
    self.params[2].parameterDependencies = [0, 1]

parameterDependencies takes a list.

The examples that follow show setting and using dependencies.

Setting dependencies examples: Clip and Add Field

Recall that the Clip tool makes a copy of the input features definition and sets the extent to the intersection of the input features and the clip features. An example of how this rule is implemented in ToolValidator is provided below. Because Clip is a built-in tool and not a script, it does not use a ToolValidator class. Built-in tools do their validation using internal routines that are essentially the same as ToolValidator. But if it did use a ToolValidator class, this is what it would look like:

def initializeParameters(self):
    # Set the dependencies for the output and its schema properties
    #
    self.params[2].parameterDependencies = [0, 1]

    # Feature type, geometry type, and fields all come from the first 
    #  dependent (parameter 0), the input features
    #
    self.params[2].schema.featureTypeRule = "FirstDependency"
    self.params[2].schema.geometryTypeRule = "FirstDependency"
    self.params[2].schema.fieldsRule = "FirstDependency"

    # The extent of the output is the intersection of the input features and 
    #  the clip features (parameter 1)
    #
    self.params[2].schema.extentRule = "Intersection"

    return

def updateParameters(self):
    return

Add Field copies the definition of an input parameter and adds the user-specified field. The link below shows how Add Field would be implemented in ToolValidator.

Setting schema in initializeParameters versus updateParameters

Note that the Clip example above modifies the Schema object in initializeParameters and that updateParameters does nothing but return. Add Field, on the other hand, has to modify the Schema object in updateParameters because it doesn't have the definition of the field to add until the user provides the information (and updateParameters is called).

You can think of these two cases as static versus dynamic. Clip doesn't rely on anything but the datasets found in the dependent parameters (static case), whereas Add Field needs to examine other parameters (such as field name and field type) that are not dependent parameters (dynamic case).

This static and dynamic behavior is evident in the way a ToolValidator class is called, as follows:

  1. When the tool dialog box is first opened, initializeParameters is called. You set up the static rules for describing the output. No output description is created at this time, since the user hasn't specified values for any of the parameters.
  2. Once the user interacts with the tool dialog box in any way, updateParameters is called.
  3. updateParameters can modify the schema to account for dynamic behavior that can't be determined from the parameter dependencies, such as adding a new field like Add Field.
  4. After returning from updateParameters, the internal validation routines are called, and the rules found in the Schema object are applied to update the description of the output data.
  5. updateMessages is then called. You can examine the warning and error messages that internal validation may have created and modify them or add warnings and errors.

Output dataset name: Cloning derived output versus required output

When you set the Schema.clone property to true, you are instructing geoprocessing to make an exact copy (clone) of the description in the first dependent parameter in the parameter dependency list. Typically, you set clone to true in initializeParameters rather than updateParameters since it only needs to be set once.

If ParameterType of the output parameter is set to Derived, an exact copy is made. This is the behavior of the Add Field tool.

If ParameterType is set to Required, an exact copy is also made, but the catalog path to the dataset is changed. Since most tools create data, this is the most common behavior.

Learning more

Programming a ToolValidator class provides details on the Parameter, Schema, and Filter objects and gives code examples.

All script-based system tools, such as Multiple Ring Buffer, have ToolValidator code from which you can examine and learn. Many of the tools in the Spatial Statistics toolbox are script tools and have ToolValidator implementation you can examine.

Temas relacionados