8

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

15

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.

3
  • Thanks for your answer, this was what I was looking for. I also have edited my question to provide more information on the topic.
    – LarsVegas
    Oct 31, 2016 at 11:13
  • 1
    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. Oct 31, 2016 at 14:45
  • Some more context and info: woostuff.wordpress.com/2013/08/31/… Sep 24 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.