1

I'm currently trying to create a function for calculating an intersect of one of two shapefiles with another shapefile. I am later looping through the list of files and, depending on which one the loop lands on, would like to call the function to run the intersect on the respective file.

My script is as follows:

new_forest = "New_Forest.shp"
south_downs = "South_Downs.shp"
noise = "RoadNoise.shp"

def noise_intersect(park):
    if park == new_forest:
        arcpy.Intersect_analysis([new_forest, noise],"nf_noise_intersect")
        return park + " intersect complete"
    elif park == south_downs:
        arcpy.Intersect_analysis([south_downs, noise],"sd_noise_intersect")
        return park + " intersect complete"

I'm pretty new to this. I feel like what I have is roughly correct but I'm just trying to see if I'm missing something. I will later try to add code to calculate area of the output file but for now need to make sure this is correct.

0

1 Answer 1

1

A couple of comments:

  1. You're relying on global variables inside your function (new_forest,south_downs, noise) which is a bad habit to get into. If your function needs a variable, pass it in as an argument.
  2. If your if is going to get much longer, it's a bit cleaner to use a dict lookup.
import arcpy


def noise_intersect(park, noise, fc_attrs):
    attrs = fc_attrs[park.lower()]  # use lowercase for comparison
    result = arcpy.Intersect_analysis([park, noise], attrs)
    return result


fcs_attrs = {  # dict with shapefile names and attributes to use in intersect
    "new_forest.shp": ["nf_noise_intersect"], # use lowercase for comparison
    "south_downs.shp": ["sd_noise_intersect"]
    "some_other_shapefile.shp": ["some_other", "yet_another"]
}
noise = "RoadNoise.shp"
arcpy.env.workspace = r"S:\ome\Directory"

for park in arcpy.ListFeatureClasses():
    result = noise_intersect(park, noise, fc_attrs)
    
    # you could get rid of the function entirely...
    result = arcpy.Intersect_analysis([park, noise], fc_attrs[park.lower()])

2
  • Thank you! I ended up getting my original function to work as intended but had been meaning to clean it up, this has definitely shown a better way to get that result. May I ask why its a bad habit to use global variables within a function?
    – Mkn
    Apr 19, 2022 at 10:00
  • They're not bad per se, but are easily misused and can cause hard to debug issues in more complex code. stackoverflow.com/questions/19158339/….
    – user2856
    Apr 19, 2022 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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