I'm attempting to create a tool that gives me the next available manhole number in a particular system. The manhole numbering structure looks like 1124-060E and therefore is a string field. Since inheriting, I've discontinued the letter extensions, because the sorting issues they cause. I've written a tool that has been working but is now spitting an error. The code is as follows:
def newMH(subbasin):
lst = []
with arcpy.da.SearchCursor(r"Sewer\Manholes",['OBJECTID','FACILITYID']) as cursor:
for row in cursor:
if subbasin.upper() in row[1].split('-')[0]:
if row[1].split('-')[1].isdigit():
lst.append(row[1].split('-')[1].zfill(6))
sorted(lst, key = lambda item: (item.isdigit(), item))
x = int(max(lst)) + 1
else:
pass
return str(subbasin).upper() +'-'+ str(x).zfill(4)
I'm saying if the 'subbasin' is equal to the first have in front of the dash then if the last half after the dash is a number then append it to my list. Then sort that list numerically then assign the max plus one to give me the next number in line then reconstruct the manhole format in my return line. The issue is the error I'm getting now.
"ERROR 000539: Error running expression: newMH('1124') Traceback (most recent call last): File "", line 1, in File "", line 13, in newMH UnboundLocalError: local variable 'x' referenced before assignment"
-
I know it is solved below for you. But it looks like the 'else' was being executed because the 'if' was failing without being able to get to lst. And in the else the x is being referenced and not defined. If you take the global lst out and set x = 0 what happens? I think you'll need both the gobal lst and x =0enolan– enolan2018年10月16日 18:41:30 +00:00Commented Oct 16, 2018 at 18:41
1 Answer 1
I couldn't replicate your error exactly, but I think this might help. Try this:
lst = []
def newMH(subbasin):
global lst
with arcpy.da.SearchCursor(r"Sewer\Manholes",['OBJECTID','FACILITYID']) as cursor:
for row in cursor:
if subbasin.upper() in row[1].split('-')[0]:
if row[1].split('-')[1].isdigit():
lst.append(row[1].split('-')[1].zfill(6))
sorted(lst, key = lambda item: (item.isdigit(), item))
x = int(max(lst)) + 1
else:
pass
return str(subbasin).upper() +'-'+ str(x).zfill(4)
I'm basing this off what I found here. I didn't look deeply into the logic of the function, just basing this off your error message.
-
That did it. It seems it's always something minor and I just couldn't see it.j.stanfield– j.stanfield2018年10月16日 18:27:11 +00:00Commented Oct 16, 2018 at 18:27
Explore related questions
See similar questions with these tags.