Python won't recognize NULL (or None)

15134
13
09-26-2011 01:11 PM
RichardThurau
Deactivated User
Hi,
Trying to calculate a field based on another field. Want to give Contiguous a "Y" where Contig_ID is not NULL.

"Calculate Field for Contiguous"
Field Name: Contiguous

Expression: Answer(!Contig_ID!)

Code Block: 
def Answer(CI):
  if CI ==None:
    return "N"
  else:
    return "Y"


I've read plenty of posts explaining that NULL == None in python, but this code only returns Y for all numeric values in Contig_ID. Where Contig_ID == Null, no values are returned to Contiguous.

Any help would be grand!

Thanks

Rich
Tags (2)
13 Replies
BarryHall
Emerging Contributor

Joshua -- many thanks -- I am a Python newbie -- does the Python None object equate to false in logical tests?

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Yes, see 2.3.1 Truth Value Testing .  Since there are several other data structures that exhibit falsy behavior, e.g., an empty string, testing for false instead of for None might result in some non-NULL fields getting treated as NULL.

BarryHall
Emerging Contributor

Why is an individual field attribute an object (re:Null is returning as a Python  None object)?

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Anything returned from any field in a cursor is a Python object because all data types are fundamentally objects:

>>> lst = [int(), float(), str(), bool(), None]
>>> for obj in lst:
...   print(isinstance(obj, object))
...
True
True
True
True
True
>>>

In terms of why NULL gets returned as None; well, None is the closest data type conceptually to SQL NULL:  Built-in Constants — Python 3.7.4 documentation 

None

The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.

0 Kudos