2

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.

  • 1
    Have you tried if pos == None? What sort of feature data are you working with? Not all data types support null (None) values. – Michael Stimson Mar 22 at 2:17
  • 1
    Python syntax is if pos is None. I Think your code is ok, easy to understand. (You could shorten it with pos = 0 if pos is None else int(pos)) – BERA Mar 22 at 6:34
  • @MichaelStimson, thanks for your comment. As a pyqgis newbie, I've already read that has some difference between none and null values in python, but I need to read more. So, I've tried your suggestion and works fine, thanks. – Francisco Camello Mar 23 at 12:20
  • @BERA, I do print('null') if pos is None else print('not null') and returns not null. I'm missing something? I liked this way of shorten conditionals, where I can find some docs to learn more about it? – Francisco Camello Mar 23 at 12:31
  • I have encountered an issue with this. In a case where pos returns {QVariant}NULL the statement if pos != None evaluates to False but if pos is not None returns True. Apparently a {QVariant}NULL equals None although it is not None. This creates an issue in variance with PEP8. – CNIDog Sep 12 at 18:50
2

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'])
  • 1
    Thanks @Joseph. Following your suggestion and @BERA way of shorten, I code this: pos = 0 if not pos else int(pos) and works fine. – Francisco Camello Mar 23 at 12:42

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.