This post outlines some of the hard rules I use when I write arcpy scripts. If you follow official arcpy documentation and forum examples you find online, it is highly possible you will end up writing bad code. This is not necessarily the users’ fault, as the package has a number of restrictions that make writing good code hard:
- Reliance on implicit state
- Incomplete support for modern
pathlibpath objects - Mix of legacy and modern interfaces (
arcpy.naandarcpy.nax) - Nonexistent integration with the native
logginglibrary - Obtuse error messages
A lot will be familiar to experienced developers, but hopefully it will save some trouble for novices.
Use modern Paths
Many arcpy operations rely on database paths built using .sde connection files for inputs/output. Unfortunately, joining paths can get very complicated in Python, especially when they are treated as string objects:
Because building paths is so fraught, Python has a native package for handling the task called pathlib. I like to represent .sde connection file paths as pathlib objects assigned to uppercase variables. This doesn’t actually do anything to the code, rather than signalling to developers that these are constants.
We can use the / operator to join these paths, which arcpy will resolve as full catalog paths.
Newer (3.7+) versions of ArcGIS Pro support passing pathlib objects natively to arcpy functions. In other cases, you’ll have to convert to a string before calling.
Don’t use workspaces…
Programming is supposed to be deterministic — as long as the inputs don’t change, a function should always produce the same outputs.
Sadly the output of an arcpy function can vary drastically depending on the workspace. In addition to worrying about passing the right parameters and variable objects, you also have to worry about the ethereal arcpy state. Consider this snippet:
The implications of running this block are huge, depending on whether arcpy.env.workspace is r"C:/batch/temp.gdb" or r"C:/batch/prod.sde". But if you look at the function call for ListFeatureClasses(), you would have no idea.
Setting a global workspace is almost always unecessary, because arcpy functions take fully quallifed paths as arguments. In the revised snippet, I treat my geodatabase location as a genuine Python object, passing the fully qualified path to ListFeatureClasses()
…use the context manager
If I need to set a workspace-level parameter, I simply wrap the code in question inside a context manager:
The context manager closes after the indented CopyFeatures() finishes, preventing you from setting a global overwriteOutput you might not want.
Use in-memory feature classes
At their most basic level, computers let us store data in memory, and do deterministic operations on them. Consider the trivial pseudo-code below:
By contrast desktop GIS users are used to working step-by-step, saving intermediate results to disk, and often doubling back to tweak parameters or redo data cleaning steps. This is the worfklow arcpy recreates — geoprocessing operations take disk files as inputs, and return “Results” objects that promise the requested operation succeeded:
To get around this, arcpy provides a “memory” workspace that allows you to avoid saving intermediate output to disk. Instead of treating this like a “workspace”, we can simply treat it as a random block of memory where our feature class is stored. And by wrapping our logic in a function, we can create something that looks more like a native Python routine.
import uuid
import arcpy
def rand_in_mem_str():
return f"memory/{uuid.uuid4()}"
def get_lake_in_county(lake_fc: pathlib.Path,
county_boundary_fc: pathlib.Path):
lake_bfr = rand_in_mem_str()
Buffer(lake_fc, lake_bfr)
lake_in_county= rand_in_mem_str()
arcpy.analysis.Clip(lake_bfr,
county_boundary_fc,
lake_in_county)
return lake_in_county
lake = r"path/to/lake"
county_boundary = r"path/to/county"
lake_in_county = get_lake_in_county(lake_fc = lake,
county_boundary_fc = county_boundary)get_lake_in_county() returns the processed feature class as an object, just like a good function should.
Use something else
Many arcpy workflows would be improved by forgoing entirely the package entirely and relying on standard data analysis tools.
At a minimum, most tabular data ops should be replaced with standard Python packages like pandas. Need to read an Excel spreadsheet of addresses, clean, rename columns, and create a feature class? Do 90% of the work in pandas in, like, 5 lines of code, then convert to a table at the last minute.
Need to run some numbers based on the attribute table of a feature class? You can materialize any file/enterprise geodatabase item as an Arrow object (data + schema with types), then convert to a dataframe using (arcpy.da.TableToArrowTable(arr).to_pandas())
polars is a fast alternative to pandas that I use on a daily basis because of its intuitive API for basic data transformation and aggregation.
I do this so often I wrote a Python package, arcpy_arrow, specifically to facilitate working with ArcGIS data and DataFrames.