0

I've never quite gotten this down. I think what this if statement does is allow a function to be run when it is called and not when the module that it is written in is imported. Take this code for example:

# Finds duplicate values in a specified feature class field and populates those reords with a 'Y' in another field

import arcpy

# enter program inputs
def findDupes(inFeatureClass, checkField, updateField, countRec = 0):
    with arcpy.da.SearchCursor(inFeatureClass, [checkField]) as rows:
        values = [r[0] for r in rows]

    with arcpy.da.UpdateCursor(inFeatureClass, [checkField, updateField]) as rows:
        for row in rows:
            if values.count(row[0]) >= 2:
                row[1] = 'Y2'
                print "yes"
            rows.updateRow(row)
            countRec += 1
            print countRec
if __name__ == '__main__':
    fc = raw_input("paste input feature class path from ArcCatolog: ") 
    fld = raw_input("duplicate field values: ")
    up = raw_input("update field: ")

    findDupes(fc, fld, up)

the module arcpy is irrelevant for this question; however, the way I'm seeing things, if I put the raw inputs at the top of the script it would still run but if I imported the script with this function as a module (import CheckforDupes) it would run upon the import statement instead of when the function was called if the __name__ == "__main__" wasn't there. Is that right?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
geoJshaun
  • 637
  • 2
  • 11
  • 32

1 Answers1

0

It allows the module to have different behavior if it's called directly from the command line vs. being imported from some other module.

In your example, if the input statements were at the top then they would always be executed, which might not be what you want if the module were being imported from somewhere else and you want to pass in the field values instead of prompting the user to type on the console.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • That's what I though. I'm trying use the function in the script after importing it as a module and now get this error: {Traceback (most recent call last): File "", line 1, in File "N:\Python\Completed scripts\Check_for_Dupes.py", line 16, in findDupes countRec += 1 UnboundLocalError: local variable 'countRec' referenced before assignment.} I've assigned countRec as global before it is called. Same result. Works fine when I run it as a script. – geoJshaun Jul 21 '16 at 21:22
  • Why are you declaring `countRec` outside of `findDupes()`? It isn't used anywhere else, so why not just put it inside the function? – John Gordon Jul 21 '16 at 21:44
  • tried using it inside and passing it as a parameter (see edited code). Also tried putting global in front of it inside the function. It is used a second time right after rows.updateRow. Same result when calling it from the interactive window. – geoJshaun Jul 21 '16 at 22:13