I have a defined function (ex. def my_function(x,y)).
def my_function(x,y):
"""algorithm"""
my_variable = my_function(filex, filey)
How can I call this variable within the code block section of the following ArcPy statement?
CalculateField_management (in_table, field, expression, {expression_type}, {code_block})
I want to include an if/elif/else statement based on the value of my_variable. For example:
if field > my_variable:
return my_variable / 2
elif field < my_variable:
return my_variable ** 2
else:
return my_variable
I think I can just include the my_variable = my_function()
at the beginning of the code block but my function is huge. Also, I don't know if CalculateField can see the function outside of the code block.
2 Answers 2
It would be pretty simple to just write a script to call your function (either, copy and paste it in, or put them in the same folder and use the import statement). I find the easiest way to call a script is from the Python window in ArcMap. That way you can easily send it layers in the TOC as arguments.
However if you are going to use it more than a few times, make a tool out of it.
import arcpy
in_table = arcpy.GetParameterAsText(0)
field = arcpy.GetParameterAsText(1)
def myfunc(x, y)
...
myvariable = myfunc(filex, filey)
expression = "myfunc(" + myvariable + ")"
codeblock = """def myfunc(my_variable)
if field > my_variable:
return my_variable / 2
elif field < my_variable:
return my_variable ** 2
else:
return my_variable"""
arcpy.CalculateField_management (in_table, field, expression, "PYTHON", codeblock)
I got this info from here: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//00170000004m000000
You can include conditional logic within Calculate Field arcpy function. The easiest way to set this up initially is:
- open up ModelBuilder
- add in the Calculate Field tool and setup your pre-logic script
- test/run model
- File>export to python script.
Explore related questions
See similar questions with these tags.