Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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. There must be a better way? Thank you for your help!

share|improve this question

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

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

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

share|improve this answer
    
I believe you have to pass in field as a argument to your myfunc function –  artwork21 Nov 14 '13 at 14:31
    
Your right, the field and the table are not defined in my example. I'm leaving that to the user, but I should have made it clear. I'll change it... –  cndnflyr Nov 14 '13 at 14:44

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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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