Customizing script tool behavior—ArcGIS Pro (2024)

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 thatis 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 arcpyclass 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
Note:

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 arcpyclass 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.

Related topics

  • ToolValidator class
  • Understanding validation in script tools

Feedback on this topic?

Customizing script tool behavior—ArcGIS Pro (2024)

FAQs

How do you set script tool parameters in ArcGIS Pro? ›

To access script tool properties, right-click the tool, click Properties, and click the Parameters tab. To add a parameter, click the first empty cell in the Label column and type the name of the parameter. This is the name that will be displayed in the Geoprocessing pane and can contain spaces.

How to make ArcPro run faster? ›

Web tool performance tips
  1. Use layers for project data.
  2. Use data local to ArcGIS Server.
  3. Write intermediate data to memory.
  4. Preprocess data used by tasks.
  5. Add attribute indexes.
  6. Add spatial indexes.
  7. Use synchronous rather than asynchronous.
  8. Avoid unnecessary coordinate transformations.

How do I create a custom toolbox in ArcGIS Pro? ›

You can create a toolbox using any of the following:
  1. Right-click a folder and select New > Toolbox (. atbx) to create a toolbox.
  2. Right-click a geodatabase and select New > Toolbox to create a toolbox.
  3. You can also create a toolbox and add it to a project.

What are script parameters? ›

A script parameter can have any of the characteristics of a custom field created through point-and-click customization. Script parameters are configurable by administrators and the users of your Suite App, and are accessible programmatically through SuiteScript.

How do I set attribute rules in ArcGIS Pro? ›

Catalog pane—Right-click a feature class or table and click Data Design > Attribute Rules. Contents pane—Right-click a layer or table and click Data Design > Attribute Rules. Ribbon—Select a layer or table in the Contents pane.

Is ArcPro faster than ArcMap? ›

ArcGIS Pro is a 64-bit multi-threaded application with powerful processing and an upgraded display engine that allows faster analysis and rendering than ArcMap.

Why is ArcGIS so slow? ›

Therefore, the performance issue could be due to any one of the reasons listed below: Numerous applications running in the background or during startup, such as, Symantec AntiVirus, Citrix, Google Chrome and so forth. Having several settings configured in ArcMap. User's home directories being redirected in Citrix.

What is the optimal path in Arcpro? ›

The optimal path created can be a flow path based on D8 flow direction. To generate an optimal path in this way, use a D8 flow direction raster as input for the Input Back Direction or Flow Direction Raster. You also need to supply an Input Distance Accumulation Raster.

What does APRX stand for? ›

Definition of APRX: Approximate or approximately.

How many tools are in ArcGIS Pro? ›

The ArcGIS Spatial Analyst extension has over 200 tools in 24 toolsets for performing spatial analysis and modeling.

How do I run a Python script in ArcGIS Pro? ›

proenv. bat—Activates the ArcGIS Pro environment and opens a command prompt window. From there, you can call arcgispro-py3\python.exe by typing Python to start an interactive terminal session, or type python followed by the name of the script you want to run.

How do I edit a Python toolbox in ArcGIS Pro? ›

To edit a Python toolbox from the Catalog pane, right-click the toolbox and click Edit. When you finish your edits, the Python toolbox is automatically refreshed when the editor is closed. Alternatively, to manually refresh a Python toolbox at any time, right-click the toolbox and click Refresh.

How do I set control points in ArcGIS Pro? ›

Add control points manually
  1. On the Georeferencing tab, in the Adjust group, click Add Control Points. ...
  2. Snap to and click the source Revit or CAD feature to create the from point. ...
  3. When the from point has been defined, the pointer prompt reads To point (target). ...
  4. Repeat steps 2 and 3 to create the second link.

How do I use tools in ArcGIS Pro? ›

Run a tool in ModelBuilder
  1. On the Analysis tab, click the ModelBuilder button . ...
  2. Drag a tool onto the model from the Geoprocessing or Catalog pane. ...
  3. Set the input and output parameters for the tool to connect your data. ...
  4. Optionally, select the Environments tab. ...
  5. Click the Validate button. ...
  6. Click the Run button.

How do I copy label parameters in ArcGIS Pro? ›

You can duplicate label classes and copy and paste labeling properties between label classes by right-clicking the label class and choosing the appropriate options from the context menu.

Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6052

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.