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 the following:

PropertyDescription

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.

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:

  • The output is the same as the input, such as Calculate Field or the example shown above. Calculate Field changes the values of a particular field on the input table—it doesn't create a new table or modify the schema of the input. Other tools whose output is the same as the input can be found in the Editing toolbox.
  • The tool modifies the schema of the input, such as Add Field. Add Field adds a field to the input table—it doesn't create a new output table.
  • The tool creates output using information in other parameters, such as the Create Feature Class tool. With the Create Feature Class tool, you specify the workspace and the name of the new feature class, and the feature class is created for you.
  • The tool outputs a scalar value as opposed to a dataset. Get Count, for example, outputs a long (the number of records). Whenever a tool outputs a scalar value, the output is Derived.
  • The tool will create data in a known location. For example, you may have a script that updates an existing table in a known workspace. The user doesn't need to provide this table in the dialog box or in scripting.

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.

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

An example of a multivalue control is illustrated below.

Multivalue control

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.

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 field names and string values for Statistic Type (GPString). By using a ValueList filter and a list of values, a drop-down list can be generated under the corresponding GPValueTable column. To set default values for a value table parameter, use the values property and provide the parameter values in a list of lists of values.

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

    param1 = arcpy.Parameter(
        displayName='Statistics Field(s)',
        name='stat_fields',
        datatype='GPValueTable',
        parameterType='Required',
        direction='Input')

    param1.parameterDependencies = [param0.name]
    param1.columns = [['Field', 'Field'], ['GPString', 'Statistic Type']]
    param1.filters[1].type = 'ValueList'
    param1.values = [['NAME', 'SUM']]
    param1.filters[1].list = ['SUM', 'MIN', 'MAX', 'STDEV', 'MEAN']

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.

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. Feature Set allows the user of your script to interactively create features in ArcMap by clicking on the map. Record Set allows your user to interactively create rows in a simple table grid.

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

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.lyrx')

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:

  • A filter only presents the user with valid choices when browsing for data. If you set a filter for point feature classes, only point feature classes are shown when the user browses for data. If you set a filter for text fields, the drop-down list of fields only shows text fields.
  • If a user types a parameter value (rather than choosing a value from the list or file browser), the value is compared to the filter. If the user enters an invalid value (a numeric field instead of a text field, for example), a warning or error occurs.

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

Filter typeValues

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, Annotation, and Dimension. More than one value can be supplied to the filter.

File

A list of file suffixes, for example, ['zip', 'xml'].

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.

Travel Mode Unit Type

A list of allowable travel mode's impedance attribute: Time, Distance, Other.

Filter type and values

PropertyDescription

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 the 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 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: true and false. The true value is always the first value in the list. The values specified in the Value list are used in Python for specifying the value. See, for example, Add Field and the NULLABLE and NON_NULLABLE keywords used for the Field IsNullable parameter.

Range

A Long or Double parameter can have a Range filter. Range filters have two values: 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 values). 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, and 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 filtersDescription

File System

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

Local Database

A personal or file geodatabase

Remote Database

An enterprise 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"]

Travel Mode Unit Type

The travel mode unit type filter can be used to set the permissible travel mode types based on the unit of the travel mode's impedance attribute. The valid options are: Time, Distance, and Other.

def getParameterInfo(self):
    param1 = arcpy.Parameter(
        displayName="Travel Mode",
        name="travel_mode",
        datatype="NetworkTravelMode",
        parameterType="Required",
        direction="Input")

     # Set the parameter to be dependent on the Network Data Source parameter
     param1.parameterDependencies = [param0.name]
     # Set the filter to accept only time-based travel modes
     param1.filter.list = ["Time"]

parameterDependencies

The parameterDependencies property has two purposes:

  • For an output dataset parameter with a derived type, the dependency is the index of the parameter from which the output is derived.
  • For certain input data types, the dependency is the index of the parameter containing the information used by the control, as shown in the table below.
# 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.

Parameter data typeDependant parameter data type

Areal Unit (GPArealUnit)

A geographic dataset used to determine the default units.

For example, a Feature Layer (GPFeatureLayer) or Raster Layer (GPRasterLayer) data type can be used.

Field (Field)

The table containing the fields.

For example, a Table View (GPTableView), Feature Layer (GPFeatureLayer), or Raster Layer (GPRasterLayer) data type an be used.

Field Mappings (GPFieldMapping)

A collection of fields in one or more input tables.

For example, a Table View (GPTableView), Feature Layer (GPFeatureLayer), or Raster Layer (GPRasterLayer) data type can be used.

Geostatistical Value Table ( GPGAValueTable)

A table of datasets and fields to be used in Geostatistical Analyst tools.

Use a Geostatistical Layer (GPGALayer) data type.

Linear Unit (GPLinearUnit)

A geographic dataset used to determine the default units.

For example, a Feature Layer (GPFeatureLayer) or Raster Layer (GPRasterLayer) data type can be used.

Network Analyst Hierarchy Settings (GPNAHierarchySettings)

The network dataset containing hierarchy information.

Use a Network Dataset (DENetworkDataset) data type.

Network Travel Mode (NetworkTravelMode)

A list of travel modes.

Use a Network Data Source (GPNetworkDataSource), Network Dataset (DENetworkDataset), or Network Dataset Layer (GPNetworkDatasetLayer) data type.

SQL Expression (GPSQLExpression)

The table containing the fields.

For example, a Table View (GPTableView), Feature Layer (GPFeatureLayer), or Raster Layer (GPRasterLayer) data type can be used.

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 (.lyrx) with the symbology property. When your tool is run, 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.lyrx')
Nota:

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

Parameters can be grouped into different categories to minimize the size of the tool dialog box or to group related parameters that will be infrequently used. Parameters that set category to the same string value will be grouped together. Several ArcGIS Network Analyst extension tools use categories, as shown below.

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.

Temas relacionados