12

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:

1

1 Answer 1

23

The NULL class is defined in the qgis.core library:

from qgis.core import NULL

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

Normally, you should be able to do a normal is None check; however, due to the 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.

Some more context and info: https://woostuff.wordpress.com/2013/08/31/qgis-2-0-dealing-with-null-values-in-pyqgis/

1
  • 3
    Good answer. Minor sidenote: None is used for invalid attributes (e.g. were not specified in setSubsetOfAttributes), so NULL was left there on purpose and the two should not be confused. Commented Oct 31, 2016 at 14:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.