Defining parameters in a Python toolbox

Almost all tools have parameters, and you set their values on the tool dialog box or within a script. When the tool is executed, the parameter values are sent to your tool's source code. Your tool reads these values and proceeds with its work.

To learn more about parameters, see Understanding script tool parameters.

In a Python toolbox (.pyt), tool parameters are defined in a tool class' getParameterInfo method by creating Parameter objects and setting their properties.

Parameter objects have many read-write properties, but the properties that should be set for every parameter include:

Property

Description

displayName

The parameter name as displayed on the tool's dialog box.

name

The parameter name as shown in the tool's syntax in Python.

datatype

Every Python toolbox tool parameter has an associated data type. When the script tool dialog box is opened, geoprocessing uses the data type to check the parameter value.

The data type is also used in browsing for data—only data that matches the parameter data type will be shown in the browse dialog box.

For a list of parameter data types, see Defining parameter data types in Python toolboxes.

While there are a wide number of available data types, the most commonly used data types include String, Double, Boolean, Feature Layer, and Raster Dataset.

parameterType

There are three choices for parameterType:

  • Required—The tool cannot be executed until a value has been supplied.
  • Optional—The parameter does not require a value.
  • Derived—The parameter is only for output parameters (see direction below). A derived output parameter does not show on the tool dialog box.

direction

This property defines whether the parameter is an input to the tool or an output of the tool.

If parameterType is set to Derived, then the parameter direction should be set to Output.

The example below defines three parameters for a tool: an input parameter that accepts a feature layer, an input parameter that accepts a new field name, and a derived output parameter based on the first input parameter. For the parameters to be reflected in the tool, return the parameters at the end of the getParameterInfo method.

def getParameterInfo(self):
    #Define parameter definitions

    # First parameter
    param0 = arcpy.Parameter(
        displayName="Input Features",
        name="in_features",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input")

    # Second parameter
    param1 = arcpy.Parameter(
        displayName="Sinuosity Field",
        name="sinuosity_field",
        datatype="Field",
        parameterType="Optional",
        direction="Input")

    param1.value = "sinuosity"

    # Third parameter
    param2 = arcpy.Parameter(
        displayName="Output Features",
        name="out_features",
        datatype="GPFeatureLayer",
        parameterType="Derived",
        direction="Output")

    param2.parameterDependencies = [param0.name]
    param2.schema.clone = True

    params = [param0, param1, param2]

    return params

Working with derived outputs

The last parameter shown above is a derived output parameter. There are five uses for a derived output parameter, as follows:

Creating multivalue parameters

If you want a parameter to be able to handle a list of values, rather than just one value, set the multiValue property to True.

In tool dialog boxes, there are two different user interface controls that are used for mulitvalues, as illustrated below.

Both types of multivalue controls are illustrated below.

Multivalue controls

Drawing from the above illustration, if the user selected all road types, the parameter value would be set to ["Interstates", "Primary roads", "Secondary roads"].

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input Features",
        name="in_features",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input",
        multiValue=True)

Creating value table parameters

Some parameters, called Value Tables, allow you to specify multiple entries. For example, you can include multiple datasets for the Input Features parameter in the Append, Union, and a number of other tools, or you can include multiple fields for the Statistics Field(s) parameter in the Dissolve and Summary Statistics tools.

Illustration of multivalue parameter control

Value table parameters are defined by setting the datatype to GPValueTable, and setting a columns property to define the data types and column headings of the parameter. In the example below, a value table parameter is defined with two columns that accept feature layers and integer values (GPLong).

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName='Input Features',
        name='in_features',
        datatype='GPValueTable',
        parameterType='Required',
        direction='Input')

    param0.columns = [['Feature Layer', 'Features'], ['Long', 'Ranks']]

To set default values for a value table parameter, use the values property, and provide the parameter values in a list of list of values.

Setting default values for a parameter

Default values can be set for a parameter by either applying a value directly with the value property, or by applying the value of an environment setting using defaultEnvironmentName.

The default value will be the contents of the parameter when the script's tool dialog box is opened. It is also the value that will be used if a # is entered for the parameter in scripting. If you don't specify value, the parameter value will be blank when the script's dialog box is opened.

Setting a default value from an environment

You can set the default value for a parameter to the value of an environment setting by setting the defaultEnvironmentName property to the name of an environment setting. Once you choose an environment setting, the value property will be ignored.

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input Workspace",
        name="in_workspace",
        datatype="DEWorkspace",
        parameterType="Required",
        direction="Input")

    # In the tool's dialog box, the first parameter will show 
    #  the workspace environment's value (if set)
    param0.defaultEnvironmentName = "workspace"

Defining parameter schema

Every output parameter of type feature class, table, raster, or workspace has a schema object. Only output feature classes, tables, rasters, and workspaces have a schema—other types do not. The schema object is created for you by geoprocessing. You access this schema through the parameter object and set the rules for describing the output of your tool. After you set the schema rules, the geoprocessing internal validation code examines the rules you set and updates the description of the output.

To learn more about working with schema, see schema topic.

When the input parameter datatype is a Feature Set or Record Set, you must specify the fieldsRule and geometryType of the features to be entered.

About Feature and Record Sets

The Feature and Record Set data types allow interactive input of data. A Feature Set allows the user of your script to interactively create features in ArcMap by clicking on the map. The Record Set allows your user to interactively create rows in a simple table grid.

Feature and Record Sets

The symbology and schema (attributes and geometry type) can be set for Feature Set and Record Set control by setting the parameter's value property to a feature class, table, or layer file (.lyr)

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input Feature Set",
        name="in_feature_set",
        datatype="GPFeatureRecordSetLayer",
        parameterType="Required",
        direction="Input")

    # Use __file__ attribute to find the .lyr file (assuming the
    #  .pyt and .lyr files exist in the same folder)
    param0.value = os.path.join(os.path.dirname(__file__),
                                "Fire_Station.lyr")

For more information on Feature and Record Sets, follow the links below.

Topic

Description

FeatureSets and RecordSets

This topic describes how to use FeatureSet and RecordSet objects in Python.

Using the interactive feature and record input controls

This topic describes how to use the Feature and Record Set controls.

Topics about Feature and Record Sets

Applying filters to a parameter

Applying a filter to a parameter allows you to narrow the choices available to the user for a parameter. For example, you can set up a field filter that limits choices to just text fields.

Geoprocessing creates filters automatically for parameters of type string, long, double, feature class, file, field, and workspace. Even if you don't set a filter for the parameter, there is still a filter associated with the parameter—it's just empty. An empty filter is the same as having no filter. By adding values to an empty filter, you activate the filter, and the user's choices are limited by the contents of the filter:

If you want only certain values or dataset types to be entered for a parameter, you can specify a filter. Set the filter's type to the appropriate value. There are six types of filters, and the type of filter you can choose depends on the data type of the parameter.

Filter type

Values

Value List

A list of string or numeric values. Used with String, Long, Double, and Boolean parameter data types.

Range

A minimum and maximum value. Used with Long and Double data types.

Feature Class

A list of allowable feature class types: Point, Multipoint, Polyline, Polygon, MultiPatch, Sphere, Annotation,and Dimension. More than one value can be supplied to the filter.

File

A list of file suffixes. Example: txt; e00; ditamap.

Field

A list of allowable field types: Short, Long, Single, Double, Text, Date, OID, Geometry, Blob, Raster, GUID, GlobalID, and XML. More than one value can be supplied to the filter.

Workspace

A list of allowable workspace types: File System, Local Database, or Remote Database. More than one value can be supplied.

Filter type and values

Property

Description

type

The type of filter (ValueList, Range, FeatureClass, File, Field, and Workspace). You can set the type of filter when dealing with Long and Double parameters (see note below). For other types of parameters, there is only one valid type of filter, so setting the type on these parameters is ignored. If you do not want to filter values, set the list property to an empty list.

list

A Python list of values for the filter. If you do not want to filter values, set the list property to an empty list.

filter properties

Usually, there is only one filter type you can choose. Only Long and Doubles have two choices: Value List and Range.

Value List

The Value List filter is very useful for providing a set of keywords. Many tools have a predefined set of keywords, such as the Field Type parameter found in Add Field, or the Join Attributes parameter of many of the tools in the Overlay toolset.

A Value List filter can be used for Long and Double data types. For these types, you enter the allowable numeric values.

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input value",
        name="in_value",
        datatype="GPLong",
        parameterType="Required",
        direction="Input")

    # Set a value list of 1, 10 and 100
    param0.filter.type = "ValueList"
    param0.filter.list = [1, 10, 100]

If you want the user to be able to choose more than one of the values, set the multiValue property to True.

A Value List can be used for Boolean data types. For Boolean data types, the Value List contains two values: the true value and false value. The true value is always the first value in the list. These values are used in the command line for specifying the value. See, for example, Add Field and the {NULLABLE | NON_NULLABLE} keywords used for the IsNullable property.

Range

A Long or Double parameter can have a Range filter. Range filters have two values: the minimum and maximum. The first value in the list is the minimum. The range is inclusive, meaning the minimum and maximum are valid choices.

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input range",
        name="in_range",
        datatype="GPLong",
        parameterType="Required",
        direction="Input")

    # Set an acceptable range of 1 to 10
    param0.filter.type = "Range"
    param0.filter.list = [1, 10]

Feature Class

For this filter, choose one or more filter values. Input feature classes will be checked against the filter values. So, for example, if you select only Point as the filter value, the user can only enter point feature classes as the parameter value.

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input Features",
        name="in_features",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input")
    param0.filter.list = ["Polygon"]

File

The file filter contains a list of file suffixes that a file may have, such as txt (simple text file) and csv (comma-separated value). You can supply any text for a suffix—it doesn't have to be a suffix that ArcGIS recognizes. The suffix can be of any length and does not include the dot.

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input File",
        name="in_file",
        datatype="DEFile",
        parameterType="Required",
        direction="Input")

    # To define a file filter that includes .csv and .txt extensions,
    #  set the filter list to a list of file extension names
    param0.filter.list = ['txt', 'csv']

Field

The field filter defines the permissible field types: Short, Long, Float, Single, Double, Text, Date, OID, Geometry, Blob, Raster, GUID, GlobalID, XML. More than one value can be supplied to the filter.

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input Features",
        name="in_features",
        datatype="GPFeatureLayer",
        parameterType="Required",
        direction="Input")

    param1 = arcpy.Parameter(
        displayName="Field",
        name="field",
        datatype="Field",
        parameterType="Required",
        direction="Input")

    # Set the filter to accept only fields that are Short or Long type
    param1.filter.list = ['Short', 'Long']
    param1.parameterDependencies = [param0.name]

Workspace

The workspace filter specifies the types of input workspaces that are permissible. There are three values:

Workspace filters

Description

File System

A system folder used to store shapefiles, coverages, INFO tables, and grids

Local Database

A personal or file geodatabase

Remote Database

An ArcSDE database connection

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input Workspace",
        name="in_workspace",
        datatype="DEWorkspace",
        parameterType="Required",
        direction="Input")

    # Set the filter to accept only local (personal or file) geodatabases
    param0.filter.list = ["Local Database"]

parameterDependencies

The parameterDependencies property has two purposes:

# Third parameter
param2 = arcpy.Parameter(
    displayName="Output Features",
    name="out_features",
    datatype="GPFeatureLayer",
    parameterType="Derived",
    direction="Output")

param2.parameterDependencies = [param0.name]
param2.schema.clone = True

You can only set parameterDependencies for certain input parameters, as shown in the table below.

Input data type

Dependant parameter data type

Description

Field or SQL Expression

Table

The table containing the fields

INFO Item or INFO Expression

INFO Table

The INFO table containing the items

Coverage Feature Class

Coverage

The coverage containing features

Area Units or Linear Units

GeoDataset

A geographic dataset used to determine the default units

Coordinate System

Workspace

A workspace used to determine the default coordinate system

Network Analyst Hierarchy Settings

Network Dataset

The network dataset containing hierarchy information

Geostatistical Value Table

Geostatistical Layer

The analysis layer containing tables

parameterDependencies data types

symbology

If the output of your tool is a feature set, raster, TIN, or Network Analyst Layer, you can specify the location of a layer file (.lyr) with the symbology property. When your tool is run from ArcMap, ArcGlobe, or ArcScene, and Add results of geoprocessing operations to the display is enabled, the output is added to the display and drawn using the symbology defined in the symbology layer file.

def getParameterInfo(self):
    param0 = arcpy.Parameter(
        displayName="Input Raster",
        name="in_raster",
        datatype="DERasterDataset",
        parameterType="Required",
        direction="Input")

    param1 = arcpy.Parameter(
        displayName="Output Raster",
        name="out_raster",
        datatype="DERasterDataset",
        parameterType="Required",
        direction="Output")

    # Use __file__ attribute to find the .lyr file (assuming the
    #  .pyt and .lyr files exist in the same folder).
    param1.symbology = os.path.join(os.path.dirname(__file__), 
                                    'raster_symbology.lyr')
NoteNote:

The layer file is read each time the tool is run. If the layer file cannot be found (because it was moved or deleted), default symbology will be used.

category

You can put parameters in different categories to minimize the size of the tool dialog box. The Network Analyst tools use categories, as shown below. Parameters with the same category string will be grouped together.

Parameter categories

Categories are always shown after noncategorized parameters. Do not put required parameters into categories, as they are hidden from view on the tool dialog box.

Related Topics

3/25/2013