Using NULL values in PyQGIS

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.

Getting ready

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.

How to do 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:

  1. First, we'll load the shapefile and access its first feature:
    lyrPth = "/qgis_data/shapes/NullExample.shp"
    lyr = QgsVectorLayer(lyrPth, "Null Field Example", "ogr")
    features = lyr.getFeatures()
    f = features.next()
    
  2. Next, we'll grab one of the NULL field values:
    value = f["SAMPLE"]
    
  3. Now, we'll check the NULL value's type:
    print "Check python value type:"
    print type(value)
    
  4. Then, we'll see whether the value is the Python None type:
    print "Check if value is None:"
    print value is None
    
  5. Now, we'll see whether it is equivalent to None:
    print "Check if value == None:"
    print value == None
    
  6. Next, we'll see whether the value matches the QGIS NULL type:
    print "Check if value == NULL:"
    print value == NULL
    
  7. Then, we'll see whether it is actually NULL:
    print "Check if value is NULL:"
    print value is NULL
    
  8. Finally, we'll do a type match to the QGIS NULL:
    print "Check type(value) is type(NULL):"
    print type(value) is type(NULL)
    

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset