When I don’t use ESRI Python module for geoprocessing – arcpy – every day, some of the idiosyncratic syntax of this (often not very Pythonic) module slips my mind. I was recently reminded of this when I ran into some problems with very short scripts. Turns out that since Python is case sensitive, you’re best bet as to which words to capitalize or camelcase, isn’t always correct. More frustrating though is the fact
>>> import arcpy
>>> sr = arcpy.Spatialreference()
Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module>
sr = arcpy.Spatialreference()
AttributeError: ‘module’ object has no attribute ‘Spatialreference’
>>> sr = arcpy.SpatialReference()
>>>
So ‘Spatialreference throws an error but ‘SpatialReference’ doesn’t. Remember to capitalize that ‘R’. ‘
SpatialReference’ is a class of the arcpy module, and classes, according to
PEP8, should be named using the CapWord (or
CamelCase) spelling convention.
So what about this …
>>> fc = "c:/temp/myfile.shp"
>>> desc = arcpy.Describe(fc)
>>> print desc.spatialreference.name
NAD_1927_StatePlane_Texas_South_Central_FIPS_4204
>>>
Apparently, here I don’t have to capitalize anything. ‘spatialreference’ works as the name of the property of dataset fc. But guess what ? So do:
>>> print desc.spatialreference.name
NAD_1927_StatePlane_Texas_South_Central_FIPS_4204
>>> print desc.SpatialReference.name
NAD_1927_StatePlane_Texas_South_Central_FIPS_4204
>>> print desc.SpatialReference.name
NAD_1927_StatePlane_Texas_South_Central_FIPS_4204
Well, that seems very inconsistent. Another one (taken from that tripped me up was:
fc = "c:/temp/dirSurvey.shp"
desc = arcpy.Describe(fc)
sr = desc.spatialReference
arcpy.CreateFeatureClass_management("C:/temp/","newFC","POLYLINE", "", "", "", sr)
Traceback (most recent call last):
File “<pyshell#14>”, line 1, in <module>
arcpy.CreateFeatureClass_management(“C:/temp/”,”newFC”,”POLYLINE”, “”, “”, “”, sr)
AttributeError: ‘module’ object has no attribute ‘CreateFeatureClass_management’
Apparently, this either used to be the correct name or some of the ESRI online documentation is wrong. But the method really is:
arcpy.CreateFeatureclass_management("C:/temp/","newFC","POLYLINE", "", "", "", sr)
Another one I keep getting wrong because I forget to capitalize is:
from arcpy import env
env.overwriteOutput = True # instead of overwriteoutput which would be wrong
To make a long story short, I’ve learned that when I can’t remember what the propert name is, I type:
>>> dir (arcpy) # or dir(arcpy.env)
and that gives me all the correct names for attributes and methods of arcpy that I need.