Can I return feature layersfrom a function?

02-28-2018 08:21 AM
Regular Contributor III

I'm creating 3 feature layers in one function. I'd like to return them from the function in a list, but as I expected, their type in the list is just string. I know I can save them out as a lyr file, but trying to avoid that if possible. Maybe they go out of scope when the function ends? Thanks.

def makeFeatureLayers():
    Make feature layers from Annotation, Polygon and Points features
    print("\nCreating feature layers")
    anno = 'Annotation'
    pt = 'Point'
    poly = 'Polygon'

    anno_path = os.path.join(ds_path, anno)
    pt_path = os.path.join(ds_path, pt)
    poly_path = os.path.join(ds_path, poly)

    fc_dict = {}
    fc_dict[anno] = anno_path
    fc_dict[pt] = pt_path
    fc_dict[poly] = poly_path

    fc_list = []

    for k, v in fc_dict.iteritems():
        lyr_name = k + '_lyr'
            arcpy.MakeFeatureLayer_management(v, lyr_name)
        except Exception as e:
            print("\nError: {}".format(e))

    for fc in fc_list:
        print("\nType of fc: {}".format(type(fc)))
Tags (2)
0 Kudos
4 Replies
Occasional Contributor

Use the getOutput() method on the MakeFeatureLayer result:

lyr = arcpy.MakeFeatureLayer_management(yourLayer).getOutput(0)
MVP Esteemed Contributor

Even using James' suggestion, you will be returning a reference to those layers and not the layers themselves.  Whether having a list of feature layer references will work for you depends on how exactly the code snippet is used in the larger workflow.  Can you elaborate on how the code snippet is being used, i.e., run in a stand-alone script, run as part of a ArcGIS Tool, etc....

0 Kudos
Occasional Contributor

Good point, another way would be to ditch MakeFeatureLayer and use arcpy.mapping.Layer instead.

0 Kudos
Regular Contributor III

This is part of a script. The layers are needed because I'm applying definition queries to them and then using them in a spatial join. The basic process is to assign annotation text to the polygon containing it, then assign the text to points within the polygon.

0 Kudos