QGIS can use NULL values as field values. Python has no concept of NULL values. The closest type it has is the None
type. You must be aware of this fact when working with Python in QGIS. In this recipe, we'll explore the implications of QGIS's NULL values in Python. The computing of a NULL value involves a pointer that is an uninitialized, undefined, empty, or meaningless value.
In your qgis_data/shapes
directory, download the shapefile from https://geospatialpython.googlecode.com/svn/NullExample.zip, which contains some NULL field values, and unzip it.
We will load the shapefile and grab its first feature. Then, we'll access one of its NULL field values. Next, we'll run through some tests that allow you to see how the NULL values behave in Python. To do this, we need to perform the following steps:
lyrPth = "/qgis_data/shapes/NullExample.shp" lyr = QgsVectorLayer(lyrPth, "Null Field Example", "ogr") features = lyr.getFeatures() f = features.next()
value = f["SAMPLE"]
print "Check python value type:" print type(value)
None
type:print "Check if value is None:" print value is None
None
:print "Check if value == None:" print value == None
print "Check if value == NULL:" print value == NULL
print "Check if value is NULL:" print value is NULL
print "Check type(value) is type(NULL):" print type(value) is type(NULL)
As you can see, the type of the NULL value is PyQt4.QtCore.QPyNullVariant
. This class is a special type injected into the PyQt framework. It is important to note the cases where the comparison using the is
operator returns a different value than the ==
operator comparison. You should be aware of the differences to avoid unexpected results in your code.