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.

migrated from stackoverflow.com Nov 14 '13 at 13:54

This question came from our site for professional and enthusiast programmers.

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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