Summary
The Editor class allows the use of edit sessions and operations to manage database transactions.
Edits are staged and not committed to the data until triggered. This allows better control if errors occur within an edit operation, or across multiple edit operations.
Discussion
Edit sessions and operations provide the following benefits:
- Group edits into atomic transactions. If an error occurs before all edits are completed, the edits can be discarded and the transaction can be rolled back.
- Optional edit operation undo and redo stacks are maintained by the geodatabase. After an edit operation is stopped, it is placed on the undo stack. The undo and redo stacks can be traversed by calling the undoOperation and redoOperation methods.
- Edit sessions and edit operations allow batched updates to occur, offering significant performance advantages when editing enterprise geodatabases.
- In geodatabases that allow multiple users to edit concurrently, an application in an edit session will not recognize changes made by other applications until the session is complete.
The Editor class can be used to start and stop distinct edit sessions and edit operations for geodatabases and shapefiles.
The startEditing method is used to start an edit session, and the startOperation method is used to start an edit operation. To commit an edit operation, call stopOperation. To cancel an edit operation, call abortOperation. To complete an edit session, call stopEditing, which accepts a Boolean parameter that indicates whether the changes made in the session should be committed or discarded.
Note:
Deviating from this pattern can cause unexpected results. For example, stopEditing should not be called while an edit operation is in progress. Instead, cancel the edit operation and stop the edit session.
Edit operations must be controlled within the context of an edit session, and edit operations cannot be nested within other edit operations.
Edit sessions and with statements
Edit sessions and operations can also be used with with statements. The with statements act as context managers and handle the appropriate start, stop, and abort calls for you. The example below highlights the basic structure of the Editor class used with with statements.
import arcpy
# Open an edit session and start an edit operation
with arcpy.da.Editor(workspace) as edit:
# <your edits>
# If an exception is raised, the operation will be aborted, and
# the edit session is closed without saving
# If no exceptions are raised, stop the operation and save
# and close the edit session
Use the undo and redo stacks
The undo and redo stacks are enabled or disabled for an edit session, depending on the Boolean parameter of the startEditing method. If an edit session will contain multiple operations that may be conditionally rolled back (and redone), the undo and redo stacks should be enabled. If not—for example, if the edit session will only contain a single operation—the undo and redo stacks can be disabled for performance benefits by setting the parameter to False.
Note:
When starting a versioned edit session in an enterprise geodatabase, the undo and redo stacks are enabled. Nonversioned edit sessions do not support undo and redo operations.
The two methods that control the undo and redo stacks are undoOperation and redoOperation. The undoOperation rolls back the state of the edit session to the last edit operation and moves the edit operation onto the redo stack. The redoOperation method moves an edit operation from the top of the redo stack back onto the undo stack and rolls the state of the edit session forward to what it was after the execution of the edit operation. When an edit operation is committed, the redo stack is cleared, making it impossible to redo any operations that may have been on the redo stack.
Situations that require an edit session
The following includes some dataset types that can only be edited within an edit session:
- Feature classes participating in a topology
- Feature classes participating in a geometric network
- Feature classes participating in a network dataset
- Versioned datasets in enterprise geodatabases
- Some object and feature classes with class extensions
Edit sessions and cursors
Cursors should be scoped to a single edit operation. This means a new cursor should be instantiated and released for each operation. This is very important when editing rows returned by a cursor because the rows are tied to a specific state of the geodatabase. Avoid using a cursor across multiple edit operations. Doing so can result in unexpected behavior and data loss.
Edit sessions and versioned data
Enterprise geodatabase tables and feature classes may be versioned. The isVersioned property can be used to determine whether a table or feature class is versioned.
When editing enterprise geodatabase tables and feature classes, the edit session mode should be set according to the type of data being edited:
- When editing a nonversioned table or feature class, set the multiuser_mode argument to False.
- When editing a versioned table or feature class, set the multiuser_mode argument to True.
Use either the Editor class or the Editor class's startEditing method to set multiuser_mode.
When multiuser mode is not set correctly, you may receive an error that objects in this class cannot be updated outside an edit session.
Syntax
Editor (workspace, {multiuser_mode})
Parameter | Explanation | Data Type |
workspace | Path to the workspace to edit. The editor can edit only one workspace at a time. | String |
multiuser_mode | When edits will be performed on versioned data, set this to True; otherwise, set it to False. Only use with enterprise geodatabases. (The default value is True) | Boolean |
Properties
Property | Explanation | Data Type |
isEditing (Read Only) | True if the Editor is in an edit session. | Boolean |
Method Overview
Method | Explanation |
__enter__ () | Starts an edit session. |
__exit__ () | If successful, stops editing and saves an edit session. If an exception, stops editing and doesn't save. |
startEditing ({with_undo}, {multiuser_mode}) | Starts an edit session. |
stopEditing (save_changes) | Stops an edit session. |
startOperation () | Starts an edit operation. |
stopOperation () | Stops an edit operation. |
abortOperation () | Aborts an edit operation. |
undoOperation () | Undo an edit operation (roll back modifications). |
redoOperation () | Redoes an edit operation. |
Methods
__enter__ ()
__exit__ ()
startEditing ({with_undo}, {multiuser_mode})
Parameter | Explanation | Data Type |
with_undo | Sets whether the undo and redo stacks are enabled or disabled for an edit session. If an edit session will contain multiple operations that might be conditionally rolled back (and redone), the undo and redo stacks should be enabled. If not—for example, if the edit session will only contain a single operation—the undo and redo stacks can be disabled for performance benefits by setting the argument to false. When starting a versioned edit session in enterprise geodatabase, the undo and redo stacks will always be enabled. Nonversioned edit sessions do not support undo and redo operations. (The default value is True) | Boolean |
multiuser_mode | When False, you have full control of editing a nonversioned, or versioned dataset. If your dataset is nonversioned and you use stopEditing(False), your edit will not be committed (otherwise, if set to True, your edits will be committed). (The default value is True) | Boolean |
stopEditing (save_changes)
Parameter | Explanation | Data Type |
save_changes | Specifies whether to save or discard changes. (The default value is True) | Boolean |
startOperation ()
stopOperation ()
abortOperation ()
undoOperation ()
redoOperation ()
Code sample
The following code uses a with statement that starts an edit operation and uses the CalculateField function on a selected set of rows in a table. Any tool errors that occur will be handled and printed.
Since the CalculateField function is performed inside a with statement, if any exceptions occur, changes will not be saved. If CalculateField completes successfully, updates will be saved.
import arcpy
fc = 'C:/Portland/Portland.gdb/Land/Parks'
workspace = 'C:/Portland/Portland.gdb'
layer_name = 'Parks'
arcpy.MakeFeatureLayer_management(fc, layer_name)
arcpy.SelectLayerByAttribute_management(
layer_name, 'NEW_SELECTION',
"""CUSTODIAN = 'City of Portland'""")
with arcpy.da.Editor(workspace) as edit:
arcpy.CalculateField_management(layer_name, 'Usage', '"PUBLIC"', 'PYTHON')
The following is an example of starting an edit session and an edit operation, creating a row in a table, and then stopping the edit operation and committing the edit session.
import arcpy
import os
fc = 'C:/projects/Portland/Portland.sde/portland.jgp.schools'
workspace = os.path.dirname(fc)
# Start an edit session. Must provide the workspace.
edit = arcpy.da.Editor(workspace)
# Edit session is started without an undo/redo stack for versioned data
# Set multiuser_mode to False if working with unversioned enterprise gdb data
edit.startEditing(with_undo=False, multiuser_mode=True)
# Start an edit operation
edit.startOperation()
# Insert a row into the table.
with arcpy.da.InsertCursor(fc, ('SHAPE@', 'Name')) as icur:
icur.insertRow([(7642471.100, 686465.725), 'New School'])
# Stop the edit operation.
edit.stopOperation()
# Stop the edit session and save the changes
edit.stopEditing(save_changes=True)
The following is an example of using the Editor class as a context manager with versioned data.
import arcpy
import os
new_students = 'C:/projects/Portland/Portland.sde/ptld.main.students_new2022'
students = 'C:/projects/Portland/Portland.sde/ptld.main.students'
# Start an edit session. Provide the workspace being acted on
# and with sde specify if data is edited in multiuser_mode.
with arcpy.da.Editor(os.path.dirname(students), multiuser_mode=True):
# If all 3 edit operations run successfully without error
# upon exiting this code block the edits will be applied to the data
arcpy.management.CalculateField(new_students , 'arrived', '2022')
arcpy.management.Append(new_students, students)
arcpy.management.CalculateField(students, "active", True)