I have been trying to calculate a field using code block in a python script. For this I am trying to set a variable for the code block called "codeblock". What I ended up finding was some interesting indentation errors before finally getting it to work. Below are two examples of code, one that didn't work and one that did work. I would like to find out why one works and the other does not.
Example 1:(DID WORK)
Codeblock = """def RemoveNull(X):
if X is None:
return 0
else:
return X"""
Example 2:(DID NOT WORK)
Codeblock = """
def RemoveNull(X):
if X is None:
return 0
else:
return X"""
The only difference between the two was where I placed the "def RemoveNull(X):"
Does anyone know why example 1 worked and example 2 did not? I would guess it has to do with the triple quotation marks, but I am unsure.
-
What GIS software are you using?Bera– Bera2018年04月11日 18:14:30 +00:00Commented Apr 11, 2018 at 18:14
-
I am creating the python script in Pyscripter. To be used for ArcGIS 10.4.JPK_GIS– JPK_GIS2018年04月11日 18:22:05 +00:00Commented Apr 11, 2018 at 18:22
-
in field calculator correct?NULL.Dude– NULL.Dude2018年04月11日 18:23:24 +00:00Commented Apr 11, 2018 at 18:23
2 Answers 2
How do you think computers know when to go to the next line?
If you think about the difference between your code examples you have put in a carriage return or new line character. A carriage return character is invisible but places text on the next line. You will see \n everywhere with respects to python as that is the new line character.
So now you know you have put in a special character this explains why one fails and the other does not, you started your function with a new line character...
-
Awesome, thank you for the answer. That seems to make sense to me.JPK_GIS– JPK_GIS2018年04月11日 21:08:59 +00:00Commented Apr 11, 2018 at 21:08
-
1I've run into this field calculator oddity from time to time. Personally I wouldn't expect that new line to cause a problem because, well, why would a new line be a problem in Python? Option 2 is better formatted and more readable and from the 'principle of least surprise' I would expect it to work. Instead you get an 'indentation error on line 2'.Alexander– Alexander2018年05月04日 12:15:14 +00:00Commented May 4, 2018 at 12:15
As noted by Hornbydd, the difference is caused by a line break. If you place example two in parentheses it can be made to work too. For example:
Codeblock = (
"""def RemoveNull(X):
if X is None:
return 0
else:
return X""")