I am developing a Python toolbox, and came across a peculiar behavior: The tool objects does not remember any instance variables between function calls. Consider this code:
import arcpy class Toolbox(object): def __init__(self): self.label = "Test" self.alias = "Test" self.tools = [Tool] class Tool(object): def __init__(self): self.label = "Test tool" self.x = "INIT" def getParameterInfo(self): param0 = arcpy.Parameter( displayName = "Parameter", name = "parameter", datatype = "String", parameterType = "Required", direction = "Input") return [param0] def updateParameters(self, parameters): self.x = "UPDATE PARAMETERS" def updateMessages(self, parameters): parameters.setWarningMessage(self.x) self.x = "UPDATE MESSAGES" def execute(self, parameters, messages): arcpy.AddMessage(self.x)
The way I would expect this code to behave is this:
__init__is called, and
xis set to
updateParametersis called, and
xis changed to
updateMessagesis called. It displays a warning with the text
"UPDATE PARAMETERS"and then change
- Finally, when the tool is executed it outputs
However, when I run the tool both the warning and the execution output is
"INIT". My conclusion is that ArcMap does not use the same instance of the class throughout, but instead creates a new instance for every function call (
Is my conclusion correct? If so, why does ArcMap behave that way? From an OOP perspective it seems very strange.
This behavior causes big problems for me. The first parameter of the tool I am developing is a text file. When the user has picked one I want to populate the other parameters with different default values depending on the content of the file. Since the file could be rather large I do not want to have to parse it every time any parameter changes, but now it seems like I have to since there is no way to know if the parameter has changed or not.