Select to view content in your preferred language

Context Manager for arcpy.mp.ArcGISProject()

493
2
03-28-2025 12:21 PM
Status: Open
Labels (1)
TylerT
by
Frequent Contributor

Add Python context manager to arcpy.mp.ArcGISProject() to properly handle the setup and cleanup of the project file and resources, ensuring that they are properly managed, even if exceptions occur.  I have encountered and read about aprx locks due to Python scripts even when project object is deleted and no exceptions occurred. 

Example syntax would be:

with arcpy.mp.ArcGISProject("project.aprx") as p:
    <do something with p>
<do something after p is cleaned up>



Thanks for listening.

Tyler

2 Comments
DanPatterson

a related "with... " request

Add Context Manager Methods to ArcPy Cursor Classe... - Esri Community

context managers all around, 

 

GIS_Spellblade

Do you know what I like doing? Iterative development. And not just committing code over time, which I also do, but I'm basically a Notebook junky. Code doesn't just pop out of my head fully formed like the goddess Athena (sometimes it does, but generally no). I run a cell, see if it gets me where I want to go (and no, I don't want to use the debugger thankyouverymuch), and then adjust, writing a bit more iteratively and happily clacking away at my keyboard. 

And this is great, usually, because I use common Python language conventions like context managers. What's not great, is being forced to do things like we're living before the Python 2.5 release. Del this. Del that. Close file. Etc. and etc. ad infinitum.

If you have an object that needs to be deleted or it causes problems, it should have a context manager. At the end of the day, the .aprx is a (zip) file. Like any other file it should have a context manager.

The documentation for the ArcGISProject and Map classes do not mention the need to delete these references within your script. Not once. Do I want the documentation updated? Sure. But more than that. I want to not have to worry about re-implementing archaic code structures (at least in Python, I'm not trying to code in C here).

Let's take this code for example, you can run it once without it breaking.

# we're doing stuff in a dir
mapx_glob = MAPX_DIR.rglob("*.mapx")
for mapx_file in mapx_glob:
    aprx = arcpy.mp.ArcGISProject(aprx_path=str(theres_a_path_here)) #Path support soon!!
    aprx.importDocument(document_path=str(mapx_file))
    aprx.save()
    mapx = aprx.listMaps()[0]
    print("we do some stuff")
    aprx.save()
    mapx.exportToMAPX(str(mapx_file))
    #del aprx
    #del mapx

When you run it again in your Notebook cell you'll be greeted with file locks. And maybe you're like me and do this a dozen times expecting different results, restarting the kernel each time, until you realize you have to use some del magic. Which is fine. I'm not salty about it. It certainly is worthy of consideration.