How do I create a global variable in a python toolbox?
The eventual purpose is that I would like to store information related to the execution of my script across functions, but not as "parameters". They might be boolean, or dictionaries, but in my example below, I am using a "String for simplicity.
Add text to the Something parameter, move to Something Else, and click Ok.
On execution, the value of self.whatever is added to the messages in ArcCatalog. It's the initial value of "ABC".
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 = "Toolbox"
self.alias = ""
# List of tool classes associated with this toolbox
self.tools = [Tool]
class Tool(object):
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
self.label = "Tool"
self.description = ""
self.canRunInBackground = False
self.whatever = "ABC"
def getParameterInfo(self):
"""Define parameter definitions"""
param0 = arcpy.Parameter(
displayName="Something",
name="something",
datatype="GPString",
parameterType="Required",
direction="Input"
)
params = [param0]
return params
def isLicensed(self):
"""Set whether tool is licensed to execute."""
return True
def updateParameters(self, parameters):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
self.whatever = "XYZ"
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."""
arcpy.AddMessage("The value whatever is: " + self.whatever)
return
Best Answer
Just write:
Without the
global
statement it will be local inside the method. Alternatively you can set a non-self variable inside the class, which I think survives the object life cycle.