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'm trying to populate a field using a function. When I run this in Pyscripter, it works fine:

d = {}

# Function #
def find_dups(val):
    d[val] = d.setdefault(val, -1) + 1
    return d[val]
#

expression = "find_dups(!LINK_ID!)"
arcpy.CalculateField_management(streets, "dups", expression, "PYTHON_9.3", "#")

However, when running it from arc toolbox I get this...

ExecuteError: ERROR 000539: Error running expression: find_dups(!LINK_ID!)

NameError: name 'find_dups' is not defined

Failed to execute (CalculateField).*

So it looks like it can't find the function. I tried using the field calculator in arc to get a python snippet and it gave me this...

arcpy.CalculateField_management(streets,"dups","find_duplicates(!LINK_ID!)","PYTHON_9.3","d = {}/n/ndef find_duplicates(val):/n d[val] = d.setdefault(val, -1) + 1/n    return d[val]/n")

When I tried to put this into my script, however, it didn't work??

ExecuteError: Failed to execute. Parameters are not valid.

ERROR 000989: Python syntax error: Parsing error

SyntaxError: invalid syntax (line 1)

Any help greatly appreciated, cheers

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Whenever you are copying a code block to a Python snippet, the new line character \n is written instead as /n which is where you are getting your syntax error. It does the same thing on my machine, running 10.1 SP1.

If you change all the forward slashes to backslashes, it should work. Another option would be to write the expression like so, as it's easier to debug and read.

exp = """d = {}
def find_dups(val):
  d[val] = d.setdefault(val,-1)+1
  return d[val]"""

arcpy.CalculateField_management(streets,"dups","find_dups(!LINK_ID!)","PYTHON_9.3",exp)
share|improve this answer
    
Aha, there it is. Knew it had to be something simple! The other option works great too - I'll use that. I see how it works now separating out the expression and the code block. Cheers Paul –  Mike Jun 27 '13 at 14:23
add comment

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.