PyQGIS 3 – Handling Field Null Values in PyQGIS for Accurate Data Management

nullpyqgispyqgis-3qgis-plugins

I've wrote a plugin and when I was tested it I found a plugin's case of use that it has to handle with null values. I've had some research and doesnt found much about it in PyQGIS3 documentation, but I read about NULL from qgis.core and write the code below:

from qgis.core import QgsProject, NULL

layer = QgsProject.instance().mapLayersByName('My_Layer_Name')[0]
selection = layer.selectedFeatures()
n_sel = layer.selectedFeatureCount()

if n_sel > 0:
    layer.startEditing()
    for feature in selection:
        pos = feature['offset_quad']
        if pos == NULL:
            pos = 0
        else:
            pos = int(feature['offset_quad'])
    # do some stuf here

I'd like to know if there is a better "pythonic" way to do this test for null values.

Best Answer

I guess a somewhat more pythonic method could be to use:

if not pos:

So something like:

layer = QgsProject.instance().mapLayersByName('My_Layer_Name')[0]
selection = layer.selectedFeatures()
n_sel = layer.selectedFeatureCount()

if n_sel > 0:
    for feature in selection:
        pos = feature['tesr']
        if not pos:
            pos = 0
        else:
            pos = int(feature['tesr'])
Related Question