Friday 31 July 2015

arcmap - Does arcpy.GetParameterAsText() have a data type?


import arcpy 
# Retrieve input parameters
inX = arcpy.GetParameterAsText(0)

inY = arcpy.GetParameterAsText(1)
inDescription = arcpy.GetParameterAsText(2)

incidentsFC = "C:/Data/Yakima/Incidents.shp"
descriptionField = "DESCR"

# Make a tuple of fields to update
fieldsToUpdate = ("SHAPE@XY", descriptionField)

# Create the insert cursor

with arcpy.da.InsertCursor(incidentsFC, fieldsToUpdate) as cursor:
# Insert the row providing a tuple of affected attributes
cursor.insertRow(((float(inX),float(inY)), inDescription))

I came across this script tool in an online course which shows an example for using the Insert Cursor where we insert a row in a point shapefile. I couldn't understand something here. Do we somehow specify what 'type' of input we will provide when we use GetParameterAsText()?


If yes, then why do we need to specify again in the last line that the coordinates given earlier are float type?


Can't we just write cursor.insertRow((inX, inY), inDescription) and if No, then how does Python understand the input in the variable inDescription is a string/text without using the double quotes anywhere?



Answer



As the name GetParameterAsText() indicates, or the documentation states, the value will be converted to text, or like we call it: a string.


Gets the specified parameter as a **text** string by its index position from the list of parameters. 


So, if the user enteres coordinates, such as 35.5432 then the tool would get understand those as '35.5432', a string. This is, however, not necessarily what we want, so, in this case, we would convert that string back to a number. As we are interested in the decimals we have to convert it to a float (not an integer, as it would chop off the decimals), and use float().


Note that you could also have converted right when getting the parameters:


inX = float(arcpy.GetParameterAsText(0))

In my opinion that makes the code easier to read, and less cluttered later on.


The important part with GetParameterAsText() is what you define in ArcGIS, when you build the tool. Here the more important, ArcGIS-internal data type, is defined. It can be daunting at first, and sometimes one has to try multiple times until finding the correct type. The interface looks like this (sorry, German interface!):


enter image description here


But the bottom line is, it would arrive in your Python as text, so sometimes conversions are necessary, such as the float() in this case!


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...