There are many things you can change about your code, but first your question.
The solution that Kadir proposes is very practical, it works for me in the console but not in the plugin, so I present you other alternatives.
Evaluate if it is a QVariant
Generally when you query the attributes of a field, it returns the data type of the field, either int, float or string, unless it is empty, so it returns an empty QVariant
.
You can simply test to see if it is a QVariant
for p in park.getFeatures():
ar = p.attributes()[6]
if type(ar)!= QVariant:
s = s + ar
Another option is the opposite, to evaluate if it gives a numerical value, but there are two conditionals:
for p in park.getFeatures():
ar = p.attributes()[6]
if type(ar)==int or type(ar)==float:
s = s + ar
Other aspects
- You can consult the
QgsFeature
as a dictionary:
for p in park.getFeatures():
ar = p[name of the field]
if type(ar)!= QVariant:
s = s + ar
- Compressing lists can make your code shorter and faster
lf=park.getFeatures()
list_values=[p[name of the field] for ar in lf if type(ar)!= QVariant]
- For optimal performance in attribute queries you should apply
QgsFeatureRequest
:
For example, configure the request so that it does not return geometries, using less memory and faster.
request = QgsFeatureRequest()
request.setFlags(QgsFeatureRequest.NoGeometry )
lf=park.getFeatures(request)
list_values=[p[name of the field] for ar in lf if type(ar)!= QVariant]