3

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.

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Nov 2, 2013 at 2:54

2 Answers 2

3

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

answered Nov 14, 2013 at 14:27
0
0

You can include conditional logic within Calculate Field arcpy function. The easiest way to set this up initially is:

  1. open up ModelBuilder
  2. add in the Calculate Field tool and setup your pre-logic script
  3. test/run model
  4. File>export to python script.
answered Nov 14, 2013 at 14:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.