Quantcast
Channel: Forums - Python
Viewing all articles
Browse latest Browse all 2485

Define a function in Tool Class of PYT

$
0
0
I'm pretty sure this is possible and I'm just missing something relatively basic.

I wrote a little function to do something (proprietary) and I want to leverage it within the execute function of a Python Toolbox. For the sake of keeping the code tidy, I'd like to define it within the Tool Class rather than within the Execute Function of the Tool Class. like so:
Code:

def updateMessages(self, parameters):
    """Modify the messages created by internal validation for each tool
    parameter.  This method is called after internal validation."""
    return

def MyFunction(inFeatureLayer):
    arcpy.SelectLayerByAttribute_management(inFeatureLayer,  "NEW_SELECTION", '"ID" = ' + "'123456'")
    SiteList = list(r[0] for r in arcpy.da.SearchCursor(inFeatureLayer, "ID"))
    return SiteList

def execute(self, parameters, messages):
    """The source code of the tool"""
    inFeatureLayer = arcpy.parameters[0].valueAsText
    Result = MyFunction(inFeatureLayer) # Why doesn’t this work???
    # Do something with the result

When I do that however, the Execute function doesn't see it. The only way I can get the execute function to see my function is by defining it within the execute function, like so:
Code:

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"""
    def MyFunction(inFeatureLayer):
        arcpy.SelectLayerByAttribute_management(inFeatureLayer,  "NEW_SELECTION", '"ID" = ' + "'123456'")
        SiteList = list(r[0] for r in arcpy.da.SearchCursor(inFeatureLayer, "ID")
        return SiteList

    inFeatureLayer = arcpy.parameters[0].valueAsText
    Result = MyFunction(inFeatureLayer) # This works, but it seems more elegant to me if I could define it outside of Execute
    # Do something with the result

This seems like it should be wholly possible. What I am doing wrong?

Viewing all articles
Browse latest Browse all 2485

Trending Articles