[GIS] Autoincrement field when New Feature added

arcgis-10.1python

I know that this is probably a very basic programming but I am brand new to Python.

I have a layer in a geodatabase that I need a unique ID field (for joining). I can't use the ObjectID because that can change. I can't use a GlobalID because the data will be used by databases that can't handle the "{" brackets or dashes.

I have already populated the field. When I add a new feature I want to have the value of the max existing value + 1 for the new feature.

Thanks to Jason here is what I have so far-

import arcpy
gdb_full_path = r'D:\GIS\ZA.gdb\Current'
feat = 'ZA_Merge'
arcpy.env.workspace = gdb_full_path
with arcpy.da.SearchCursor(feat,["ANID"]) as cursor:
     for row in cursor:
         unique_id_counter = row.count
with arcpy.da.InsertCursor(feat,["ANID"]) as cursor:
     cursor.insertRow((unique_id_counter + 1))

Here is the error that I get –

Runtime error
Traceback (most recent call last):
File "", line 9, in
TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'int'

Best Answer

Here is a basic example of how you can add a new feature to a feature class with an incremental unique ID based on the last feature in said feature class:

import arcpy

gdb_full_path = r'c:\full\path\to\your\geodatabase.gdb'
feat = 'feature_class'

arcpy.env.workspace = gdb_full_path

# create a search cursor so we can read the rows of the feature class
with arcpy.da.SearchCursor(feat,['name_of_unique_id_field']) as cursor:
    for row in cursor:
        # for each row, we read the unique ID...once we get to the end our
        # new variable, "unique_id_counter", will be equal to the value of the
        # last feature
        unique_id_counter = row.name_of_unique_id_field

# create an insert cursor to add new features to the feature class
with arcpy.da.InsertCursor(feat,['name_of_unique_id_field']) as cursor:
    # insert a new row and populate the unique ID field with a new value
    cursor.insertRow( (unique_id_counter+1) )