Export a model to Python

Exporting a model to a Python script can help you learn how tools and environments are used in Python. To export a model to Python, click the Export button on the ModelBuilder ribbon and choose one of the following options:

  • Export To Python File
  • Send To Python window

Both options will generate the same Python code. The code can be further edited and used as a stand-alone Python script, or modified to work as a script tool.

Considerations for model to Python export

When exporting a model to a Python script, a number of considerations are made to adapt the model to Python code. The following describes some of these considerations.

Overwrite

By default, a model exported to Python sets the overwriteOutput property to False. To support overwriting any output dataset, set the arcpy.env.overwriteOutput property to True.

Code organization

With the exported script, a model is exported as a function and the parameter values are passed as arguments, such as:

def Model(InputFC=r"C:\Data.gdb\inFC", Output="C:\Output.gdb\outFC", Extent="1186925.51155726 -2378062.72079588 1240005.19719053 -2315230.04252389", Name="Canada Goose"):

If the model included submodels, the contents of those submodels are exported into separate subfolders. The primary Python file will correctly import and call the submodel Python file during the code run.

Extensions

The CheckOutExtension function is added for tools that have extension requirements.

Layers and table views

If the model uses layers or table views that weren't created within the model, you'll need to create those layers or table views in the script using tools such as Make Feature Layer and Make Table View.

Validation

Data elements in the model are converted to variables in the Python script. Variable names with incompatible characters, such as [({*^%$#@!&*,.";:/\, will be validated to exclude the incompatible characters. Variable values with incompatible characters will be retained as is. Avoid naming data elements that are reserved keywords in Python, for example, class, global, and return. For a full list of reserved keywords, use the Python keyword module's kwlist property.

  • Variables names with incompatible characters, such as Input Features A_ [({*^%$#@!&*,.";:/\, will be validated to Input_Features_A_. Variable values with incompatible characters will be retained as is, for example, Input_Features_A_ = "A_ [({*^%$#@!&*,.\";:/\\". Avoid naming data elements that will be incompatible in Python (for example, class, global, and return). For a full list of reserved keywords, use the Python keyword module's kwlist property.

Variable substitution

Models containing inline variable substitution will be exported to Python as given below:

  • Inline variable substitution Type = '%Name%' in an expression builder for tools such as Select Layer By Attribute will be exported as where_clause=f"Type = '{Name}'".
  • Inline variable substitution for a workspace %Output Workspace%\a or %scratchGDB%\b will be exported as OutputFC = fr"{Output_Workspace}\a" and OutputFC = fr"{arcpy.env.scratchGDB}\b".
  • System inline variable substitution, such as %n% and %i%, will be passed as a string.
  • A variable with inline variable substitution and set as a model parameter will be evaluated using the Python built-in functions locals(), globals(), and isinstance() when exported to Python, for example:
    arcpy.analysis.Buffer(in_features=_Name_.__str__().format(**locals(),**globals())if isinstance(_Name_, str) else _Name_, out_feature_class=Name_Buffer, buffer_distance_or_field="10 Meters")

Data types

Data types in model when exported to Python are mapped as given below:

  • String, Long, Double, and Boolean data type model variables values are mapped to Python data types. All other data type values are mapped as strings in Python.
  • Value table parameter values are mapped as a list, for example:
    arcpy.Statistics_analysis(in_table=a, out_table=b, statistics_fields=[["Type", "COUNT"], ["Year", "COUNT"]], case_field=["Type"])
  • Field mapping parameters, such as the Append tool's Field Map parameter, will be converted to a semicolon-delimited string, as follows:
    field_mapping="Type \"Type\" true true false 20 Text 0 0,First,#,InputFC,Type,0,20;Year \"Year\" true true false 2 Short 0 0,First,#,InputFC,Year,-1,-1)

Environments

Only the environment settings that have been changed from the default value will be exported to Python for the application, model, and the tool. The exported script sets environments using the EnvManager class within a with block; the environment setting values are temporary, and are only set for the duration of the with block.

import arcpy

def GnatcatcherHabitat():  # Gnatcatcher Habitat

    # Model Environment settings
    with arcpy.EnvManager(extent="3434731.64703611 -1534445.99025604 3485825.15860115 -1466080.56806995")

        # Process: Buffer (Buffer) 
        with arcpy.EnvManager(extent="1187538.76766617 -2377527.90888239 1230418.76331601 -2319961.0344503")
            arcpy.Buffer_analysis(in_features=r"C:\Data.gdb\A", out_feature_class=r"C:\Output.gdb\B", buffer_distance_or_field="500 Meters", line_side="FULL", line_end_type="ROUND", dissolve_option="NONE",dissolve_field=[], method="PLANAR")

if __name__ == '__main__':
    # Global Environment settings
    with arcpy.EnvManager(scratchWorkspace=r"C:\Output.gdb\", workspace=r"C:\Data.gdb\"):
        GnatcatcherHabitat()

Model flow

  • Model preconditions are converted to an if block:
    if a and b:
        arcpy.Buffer_analysis(in_features=inFC, out_feature_class=outFC, buffer_distance_or_field="10 Meters", line_side="FULL", line_end_type="ROUND", dissolve_option="NONE", dissolve_field=[], method="PLANAR")
  • Model feedback loops are translated into the script flow.

Model tools

Model tools Iterators, Utilities, or Logical will not be exported to Python. You will need to add equivalent Python functionality that these tools provide. For example, you will need to use if/else logic to perform conditional branching in your script.

Derived outputs

Derived output values are assigned to variables by indexing the Result object of a geoprocessing tool, as follows:

output = arcpy.JoinField_management(in_data=infc, in_field="Type", join_table=joinTable, join_field="Type", fields=["Year"])[0]