0

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 Apr 11 '18 at 18:14
  • I am creating the python script in Pyscripter. To be used for ArcGIS 10.4. – JPK_GIS Apr 11 '18 at 18:22
  • in field calculator correct? – NULL.Dude Apr 11 '18 at 18:23
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 Apr 11 '18 at 21:08
  • I'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 May 4 '18 at 12:15
0

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""")

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.