I am unclear on why one should use QgsFeatureRequest() when iterating over a file’s features.

Let’s say I would like to print out all IDs in my currently active dataset. Now, most examples will provide something like this:

lyr = iface.activeLayer()
prov = lyr.dataProvider()
for feature in prov.getFeatures(QgsFeatureRequest()):
    print feature.id()

Whereas the following, without referring to QgsFeatureRequest(), would yield the same result:

lyr = iface.activeLayer()
prov = lyr.dataProvider()
for feature in prov.getFeatures():
    print feature.id()

I’d assume that the right way is using QgsFeatureRequest(), as most quality sources include it, but can someone explain what it actually does, and why one should use it?

2 Answers 2


As you can see in the QGIS API docs, when you call getFeatures() with no arguments, QGIS gets a QgsFeatureRequest() by default.

That is, QgsFeatureRequest() is the default value for the first argument of getFeatures(). You can choose whether or not passing it, the result is the same.

Also from the docs, by calling QgsFeatureRequest() you:

construct a default request: for all features get attributes and geometries.

However, if you want to pass a filter expression to getFeatures(), you must pass a QgsFeatureRequest(expression) as done in How to select and zoom in features from a QGIS Python Plugin.

  • 1
    That cleared things up for me, thank you. I am still not used to reading this kind of documentation, so thank you for explaining how one would approach such a question! So, basically: when setting a filter expression => QgsFeatureRequest() must be used, when just iterating => QgsFeatureRequest() is optional. So, I guess the reason that you see it so often in iteration examples, is mainly so that one gets used to it, and does not forget it later on, when it becomes necessary. Or that the code looks more complete. Jan 28, 2015 at 8:12
  • Right, it might be for developers to be aware of the optional function argument. After the first time, you probably won't use it if not necessary. Jan 28, 2015 at 13:44

You could also use QgsFeatureRequest() to only request the feature attributes you need for a certain operation. For large feature updates this can somewhat reduce execution time.

Here is an example, taken directly from this blog post:

delta_x = 0.1
delta_y = .3
vlayer = iface.activeLayer()
u = QgsVectorLayerEditUtils( vlayer )

for f in vlayer.getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest.NoGeometry ).setSubsetOfAttributes([]) ):
        u.translateFeature( f.id(), delta_x, delta_y )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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