1

I have been trying to access the values of the attributes of certain features in a vector layer. I have tried to to as they suggest in How to read the attribute values using PyQGIS? and Getting feature attribute description with pyqgis?, but whenever i try to define the feature with next(), i get StopIteration exception. This stops my program as if it was an error. I have been working on it for quite some time, but I haven't been able to find a way around it.

Is there a way to get attribute values from specific features of the vector layer without getting stoped by "StopIteration"?

I am working in QGIS 2.18

EDIT, Code snippit:

for i in range(0, len(vaiable)):
    request = QgsFeatureRequest().setFilterFid(i)
    iterator = layer.getFeatures(QgsFeatureRequest().setFilterFid(i))
    feature = next(iterator)
    #feature = layer.getFeatures(request).next()

I have tried with both iterator and request, with but StopIterator is raised when trying to assign "feature" in both cases

1 Answers1

1

It's quite hard to know, what exactly you have in vaiable. I assume it's an array, and given the array is [1,2,3], i would iterate over 0,1,2.

Your code is based on the assumption, that there is a feature for each of these three ids (0, 1 and 2), but the StopIteration tells us that this assumption does not hold true. At some point, the code tries to get a feature on an empty iterator.

The following code will help to get more information which ID is not there. If you just want to ignore non-existent features, remove the raise.

for i in range(0, len(vaiable)):
    request = QgsFeatureRequest().setFilterFid(i)
    iterator = layer.getFeatures(QgsFeatureRequest().setFilterFid(i))
    try:
        feature = next(iterator)
    except StopIteration:
        print('No feature with id {} found in dataset').format(i)
        raise
    #feature = layer.getFeatures(request).next()

To check which ids the features on the layer have, use this code:

print(', '.join(str(f.id()) for f in layer.getFeatures()))
Matthias Kuhn
  • 27,780
  • 3
  • 88
  • 129
  • The variable changes and is supposed to be an feature for each of the ids. I did try the test, and the exception is raised already at id 0. I have been trying this in qgis console with different numbers, and StopIteration is always stopping the code – Kasper Skjeggestad Oct 18 '18 at 10:23
  • What is the output of print(', '.join(str(f.id()) for f in layer.getFeatures()))? That will print all the ids which are available on the layer. – Matthias Kuhn Oct 18 '18 at 10:28
  • 1
    It prints out a long list of ascending numbers (6, 16, 28, 47, 55, 77, 91, 99, 129 ... ). So, the feature ids doesn't necessarily start at 0 or 1 then? I suppose that's where I went wrong. I will rethink the code with this information. Thank you for your help – Kasper Skjeggestad Oct 18 '18 at 10:43