Select to view content in your preferred language

Python if elif always defaults to elif

948
4
Jump to solution
03-13-2023 11:49 AM
ThomasColson
MVP Frequent Contributor

With the following I am evaluating: 

  • Does the field exist and correct length. Print message
  • Does the field exist and incorrect length. Print message
  • Does the field not exist. Create field. Print Message
#Create required TRLNAME Field
try:
        in_Field = "TRLNAME"
        if len(arcpy.ListFields(in_Table,in_Field))>0 and len(in_Field) == 254:
                arcpy.AddWarning(in_Field+" exists and is the correct length. Yay!")
        elif len(arcpy.ListFields(in_Table,in_Field))>0 and len(in_Field) != 254:
                arcpy.AddWarning(in_Field+" exists but is not the correct string length (254).")
        else:
                arcpy.AddField_management(in_Table, in_Field, "TEXT", "", "", 254, in_Field, "NON_NULLABLE", "REQUIRED", "")
                arcpy.AddMessage ("Created the "+in_Field+" field.")
except arcpy.ExecuteError:
        msgs = arcpy.GetMessages(2)
        arcpy.AddError(msgs)
except:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

 If the field does not exist, it correctly creates it. However, if the field exists, regardless of if it's the correct length (254 or any other string length), it always defaults to the "elif" in the block and reports that the field is not the correct length. 

Feel like this is a simple syntax error but I've been at it for hours and not seeing it. Help?

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
Mahdi_Ch
Regular Contributor

The problem is in the second part of the if statement. You defined the "in_Field"  variable on the 3rd line and that's a string. So length of that string will always be 7 (number of letters in the TRLNAME) and that will never change, so it never meets the criteria of being equal 254. You want to test the field properties not its name.

I will probably do something like this and also separate the check for field existence from the field length check.  I wrote the basic idea and you need to replace the print statement with whatever you want to do. 

 

if len(arcpy.ListFields(in_Table, in_Field))>0:
    if arcpy.ListFields(in_Table, in_Field)[0].length == 254:
        print('254 should fall into this now!')
    else: 
        print('other lengths should fall into this!')
else:
    print('Create new')

 

if the field exists, arcpy.ListFields() will return a list and that field (as an object) is an element of that list, so you get the first item on that list ([0]) and check the length of that.

Sometimes it easy to not spot the problem in your code right away! In that case, just stop, take a walk and come back a few min later you will probably see it 🙂

View solution in original post

4 Replies
by Anonymous User
Not applicable

Ah, I think you mean to get the length of the field and not length of the field name.  Sorry about that- 

 

fld = arcpy.ListFields(in_Table, in_Field)

if fld:
    if fld[0].length == 254:
        arcpy.AddWarning(in_Field + " exists and is the correct length. Yay!")
    else:
        arcpy.AddWarning(in_Field + " exists but is not the correct string length (254).")
else:
    arcpy.AddField_management(in_Table, in_Field, "TEXT", "", "", 254, in_Field, "NON_NULLABLE", "REQUIRED", "")
    arcpy.AddMessage("Created the " + in_Field + " field.")

 

 

Mahdi_Ch
Regular Contributor

The problem is in the second part of the if statement. You defined the "in_Field"  variable on the 3rd line and that's a string. So length of that string will always be 7 (number of letters in the TRLNAME) and that will never change, so it never meets the criteria of being equal 254. You want to test the field properties not its name.

I will probably do something like this and also separate the check for field existence from the field length check.  I wrote the basic idea and you need to replace the print statement with whatever you want to do. 

 

if len(arcpy.ListFields(in_Table, in_Field))>0:
    if arcpy.ListFields(in_Table, in_Field)[0].length == 254:
        print('254 should fall into this now!')
    else: 
        print('other lengths should fall into this!')
else:
    print('Create new')

 

if the field exists, arcpy.ListFields() will return a list and that field (as an object) is an element of that list, so you get the first item on that list ([0]) and check the length of that.

Sometimes it easy to not spot the problem in your code right away! In that case, just stop, take a walk and come back a few min later you will probably see it 🙂

ThomasColson
MVP Frequent Contributor

Thanks this worked!

ThomasColson
MVP Frequent Contributor

With the following I am evaluating: 

  • Does the field exist and correct length. Print message
  • Does the field exist and incorrect length. Print message
  • Does the field not exist. Create field. Print Message
#Create required TRLNAME Field
try:
        in_Field = "TRLNAME"
        if len(arcpy.ListFields(in_Table,in_Field))>0 and len(in_Field) == 254:
                arcpy.AddWarning(in_Field+" exists and is the correct length. Yay!")
        elif len(arcpy.ListFields(in_Table,in_Field))>0 and len(in_Field) != 254:
                arcpy.AddWarning(in_Field+" exists but is not the correct string length (254).")
        else:
                arcpy.AddField_management(in_Table, in_Field, "TEXT", "", "", 254, in_Field, "NON_NULLABLE", "REQUIRED", "")
                arcpy.AddMessage ("Created the "+in_Field+" field.")
except arcpy.ExecuteError:
        msgs = arcpy.GetMessages(2)
        arcpy.AddError(msgs)
except:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)

 If the field does not exist, it correctly creates it. However, if the field exists, regardless of if it's the correct length (254 or any other string length), it always defaults to the "elif" in the block and reports that the field is not the correct length. 

Feel like this is a simple syntax error but I've been at it for hours and not seeing it. Help? 

Tags (3)
0 Kudos