Wait for AddField to finish until running CalculatField

2142
10
Jump to solution
04-14-2017 06:05 AM
TimWitt2
MVP Alum

Hey everybody,

I am creating python toolbox and one of the tools adds a bunch of fields to a feature class that the user chooses and after wards calculates those fields with values from the original feature class. I run into the issue that the field calculations can't run because the fields haven't been added yet.

This is the code I use:

import arcpy  
  
class Toolbox(object):  
    def __init__(self):  
        """Define the toolbox (the name of the toolbox is the name of the .pyt file)."""  
        self.label = "My first python toolbox"  
        self.alias = "Examples"  
  
        # List of tool classes associated with this toolbox  
        self.tools = [Tool1]  
  
class Tool1(object):  
    def __init__(self):  
        """Define the tool (tool name is the name of the class)."""  
        self.label = "Nena Street Tool"  
        self.description = "Example showing how to create a value table tool with drop downs"  
        self.canRunInBackground = False  
  
    def getParameterInfo(self):  
        """Define parameter definitions"""  
  
        
        # Define Parameter 0  
        
  
        # Param0 will be a FeatureLayer 
        param0 = arcpy.Parameter(displayName = "Your Street Layer",name="Site_layer",datatype="GPFeatureLayer",parameterType="Required",direction="Input")          

        
        # Define Parameter 1  
        
  
        param1 = arcpy.Parameter(displayName = "",name="Activity_layers",datatype="GPValueTable",parameterType="Optional", direction="Input")  
  
 
        param1.columns=[["String","NENA Field"],["String","Your Field"]]  
  
  
        # This says the filter on the second column will be a value List  
        param1.filters[1].type="ValueList"
        param1.value = "Source; Updatedate; Effective; Expire; RCL_NGUID; AdNumPre_L; AdNumPre_R; FromAddr_L; ToAddr_L; FromAddr_R; ToAddr_R; Parity_L; Parity_R"          
  
        # This adds a dummy value to the list, this will get overwritten by the updateParameters function  
        param1.filters[1].list=["Please Select a street layer"]  
  
        # Create a list of parameters and return  
        params = [param0,param1]  
        return params  
  
    def isLicensed(self):  
        """Set whether tool is licensed to execute."""  
        return True  
  
    def updateParameters(self, parameters):  

  
        if parameters[0].altered:
          fields = arcpy.ListFields(parameters[0].value)
          mylist = []
          for field in fields:
             mylist.append(field.name)
          parameters[1].filters[1].list = mylist
        return  
  
    def updateMessages(self, parameters):  
        """Modify the messages created by internal validation for each tool 
        parameter.  This method is called after internal validation."""  
        return  
  
    def execute(self, parameters, messages):  
        """The source code of the tool."""  
        try:  
            # Some code to show that I had managed to get what I wanted intot the ValueTable               
            data = parameters[1].values
            arcpy.AddField_management(parameters[0].value, "Source", "TEXT", "", "", "75", "", "NULLABLE", "NON_REQUIRED", "")
            arcpy.AddField_management(parameters[0].value, "DateUpdate", "DATE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
            arcpy.AddField_management(parameters[0].value, "Effective", "DATE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
            search = 'Source'
            for sublist in data:
              if sublist[0] == search:
                final = sublist
                mysource = final[1]
                sourceData = "[" + mysource + "]"
                arcpy.CalculateField_management(parameters[0].value, "Source", sourceData, "VB", "")
                break

        except arcpy.ExecuteError:  
            messages.addErrorMessage(arcpy.GetMessages()) 

In line 75 I add the "Source" field and in line 84 I try to calculate it, but I get the error that the "Source" field does not exist.

Any help would be appreciated.

Tim

Tags (2)
0 Kudos
10 Replies
curtvprice
MVP Esteemed Contributor

You're welcome!

I will have to do that for 40 fields I am looking for any way to speed up my code.

Given your application (it sounds like you need to populate these fields from existing fields with different names, maybe parts of field content too), you may want to consider setting up a field map, add your 40 fields to it, and running Feature Class To Feature Class. Field maps are a bit tricky to work with but I'm certain this is the fastest way to add 40 fields to a table and copy content over from existing fields.

That ExtendTable thing is awesome though!