Update cursors and feature datasets

319
3
06-28-2018 12:22 AM
DaleRichter
New Contributor II

Having a problem using an update cursor to add values to a field in a feature class that is in a feature dataset and has topology.  This code always works outside of a feature dataset and sometimes works inside a feature dataset without topology.

            UPDATE_FIELD = [error_field] + KEY_FIELD
            with arcpy.da.UpdateCursor (features, UPDATE_FIELD) as cursor:
                for row in cursor:
                    key = tuple (row [1:])
                    if key in error:
                        row [0] = error [key]
                        cursor.updateRow (row)
            del cursor

Any help would be appreciated. 

0 Kudos
3 Replies
JoshuaBixby
MVP Esteemed Contributor

Anytime something "sometimes" works, it is always more challenging to sort out.  When it doesn't work, what is the result?  Do you get error messages or unexpected results?  Sharing the specifics is helpful.

Looking at the code, you use KEY_FIELD but you don't show it as being defined anywhere.  How is that variable setup?

0 Kudos
DaleRichter
New Contributor II

The KEY_FIELD is defined, that was just an incomplete snippet of the code.  Here is some example code with error message:

>>> p = r'D:\_RE_MAKE_TEST\eiu.gdb\albers\pre'  # belongs to pre_Topology

>>> UPDATE_FIELD = ["ERROR"]

>>> features = p

>>> with arcpy.da.UpdateCursor (features, UPDATE_FIELD) as cursor:

...     for row in cursor:

...         x = row

...        

Runtime error

Traceback (most recent call last):

  File "<string>", line 2, in <module>

RuntimeError: Objects in this class cannot be updated outside an edit session

>>> 

I think I have found a solution.  If I do the update cursor inside an edit session it works.  Which is a bit messy but it works.  Not having used this approach before does this code look alright?

def update_error_field_EDIT (features, UPDATE_FIELD, error):
    fds = os.path.dirname (features)
    assert "FeatureDataset" == arcpy.Describe(fds).dataType
    gdb = os.path.dirname (fds)
    assert is_geodatabase (gdb)
    edit = arcpy.da.Editor (gdb)
    edit.startEditing (False, False)
    edit.startOperation ()
    update_error_field (features, UPDATE_FIELD, error)
    edit.stopOperation ()
    edit.stopEditing (True)
    del edit
    return

 

JoshuaBixby
MVP Esteemed Contributor

If your feature class is in a feature dataset that has either a network or topology defined, then I believe you have to use an edit session, as the error indicates.

0 Kudos