0

Script is simple made for this case. Creating new shapes based on known arguments.

My code:

import arcpy

#variables
fc_1 = 'fc_1'
fc_2 = 'fc_2'
fc_3 = 'fc_3'
fc_4 =  'fc_4'
war_1 = "highway = 'path'"
war_2 = "highway = 'motorway'"
war_3 = "natural = 'water'",
war_4 = "leisure = 'pitch'",
suffix_1 = '1'
suffix_2 = '2'
suffix_3 = '3'
suffix_4 = '4'
temp = 'temp_layer'

def select_save(fc, temp, war, suffix):
    arcpy.MakeFeatureLayer_management(fc, temp)
    arcpy.SelectLayerByAttribute_management(temp, "NEW_SELECTION", war)
    arcpy.CopyFeatures_management(temp, '{0}_{1}'.format(fc, suffix)

arcpy.env.workspace = r'gdb_path'

select_save(fc_1, temp, war_1, suffix_1)
select_save(fc_2, temp, war_2, suffix_2)
select_save(fc_3, temp, war_3, suffix_3)
select_save(fc_4, temp, war_4, suffix_4)

So how to get rid of those copy-pasted function calls? In my current project I need to call my function 20-30 times. It looks horrible to see this wall of text.

0

To do so I used itertools.starmap function:

https://docs.python.org/2/library/itertools.html#itertools.starmap

Why starmap not map?

Starmap eliminates need of using lambda function to iterate through tuple.


I started off with tuple which contains all arguments needed to call starmap.

tuple_args = [(fc_1, temp, war_1, suffix_1),
          (fc_2, temp, war_2, suffix_2),
          (fc_2, temp, war_3, suffix_3),
          (fc_3, temp, war_4, suffix_4)]

Final code looked like this:

import arcpy
from itertools import starmap
arcpy.env.overwriteOutput = True

#variables
fc_1 = 'fc_1'
fc_2 = 'fc_2'
fc_3 = 'fc_3'
fc_4 =  'fc_4'
war_1 = "highway = 'path'"
war_2 = "highway = 'motorway'"
war_3 = "natural = 'water'",
war_4 = "leisure = 'pitch'",
suffix_1 = '1'
suffix_2 = '2'
suffix_3 = '3'
suffix_4 = '4'
temp = 'temp_layer'

def select_save(fc, temp, war, suffix):
    arcpy.MakeFeatureLayer_management(fc, temp)
    arcpy.SelectLayerByAttribute_management(temp, "NEW_SELECTION", war)
    arcpy.CopyFeatures_management(temp, '{0}_{1}'.format(fc, suffix)

arcpy.env.workspace = r'gdb_path'

tuple_args = [(fc_1, temp, war_1, suffix_1),
          (fc_2, temp, war_2, suffix_2),
          (fc_2, temp, war_3, suffix_3),
          (fc_3, temp, war_4, suffix_4)]

list(starmap(select_save, tuple_args))

Remeber to put starmap(...) inside of list, beacuse if not there will be no output and you will see something like this:

map at 0x2002a48c588

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.