[GIS] Importing NULL in PyQGIS

importnullpyqgis

This resource shows how to use NULL values in PyQGIS. Within the Python Colsole the comparison value == NULL passes without exception. However, when run from my plugin NULL is neither in the global nor the local namespace:

NameError: global name 'NULL' is not defined

The only way to check for NULL values seems to be to check for an instance of QPyNullVariant:

from PyQt4.QtCore import QPyNullVariant

if isinstance(value, QPyNullVariant):
    pass 

How do I import NULL so I can compare value == NULL?

For those wondering why and how NULL is different from None have a look at this blog entry. Essentially historically is wasn't possible to return None:

Turns out by removing QVariant from PyQt it had some impact on methods that expected a NULL QVariant – A QVariant with no value. Passing None didn't work because those methods needed the type information that QVariant holds, even when NULL.

On None comparisons it says:

One way to check if something is Null in Python is to use value is None however this will not work with our NULL type. Overloading the is operator in Python is not supported and there is no way we can support this – trust me I have tried. is is really doing id(object) == id(object) under the hood:

Best Answer

The NULL class is defined in qgis.core:

import qgis.core

if f["SAMPLE"] == qgis.core.NULL:
   ...

Normally you should be able to do a normal is None check however due to tool we use to generate the Python API it will convert null values on the C++ side (which is what QGIS is written in) to QPyNullVariant. We tried to talk the PyQt devs around to making it just return None but didn't have much luck.

Related Question