This question is very related to the unanswered Retrieve features from QgsFieldExpressionWidget pyqgis

I have a layer and I've build a QgsExpression that involves a field of that layer. What I'm trying to do is to evaluate the expression and get the results as a single list.

The problem is that I'm trying to do this with QGIS master (so the future 3 version) and the instruction of the PyQGIS cookbook are outdated because some API are changed.

Just to have an example:

vl = iface.activeLayer()
exp = QgsExpression('PH > 7') # where PH is the name of a field

# then I get this error

Traceback (most recent call last):
  File "/usr/lib/python3.5/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
TypeError: QgsExpression.prepare(): argument 1 has unexpected type 'QgsFields'

Someone has already successfully used the QgsExpression for QGIS master?


In QGIS 3.0, you may need to use a combination of the QgsExpressionContext and QgsExpressionContextScope classes:

vl = iface.activeLayer()
features = [feat for feat in vl.getFeatures()]

context = QgsExpressionContext()
scope = QgsExpressionContextScope()
listOfResults = []

for feat in features:
    exp = QgsExpression('PH > 7')

The output is boolean, either 0 (false) or 1 (true), and stored in a list:

>>> [0, 0, 0, 1, 1, 1]
| improve this answer | |
  • 2
    context.appendScope(scope) line should be moved outside of the loop. Otherwise QGIS crashes. – Kadir Şahbaz Oct 14 '18 at 18:54

I used your code in my QGIS Python Console (with a shapefile with 'PH' field; only one value > 7) and I got a result (see next image).

enter image description here

So, I printed 'vl.pendingFields()' to find out what kind of object is:

<qgis._core.QgsFields object at 0x17E10E40>

and afterward, a help for QgsExpression.prepare for corroborating wich parameters it uses:

Help on built-in function prepare:

    QgsExpression.prepare(QgsFields) -> bool
    QgsExpression.prepare(QgsExpressionContext) -> bool

In my case, used parameter is correct and the result was as expected. So, I suggest that you use 'help' command with your QGIS future 3 version to find out the new kind of parameters to use.

| improve this answer | |
  • HI. thanks for the answer. I think that the use of prepare is deprecated in QGIS 3. The help function return my: prepare(...) Get the expression ready for evaluation - find out column indexes. \param context context for preparing expression .. versionadded:: 2.12 :rtype: bool – matteo Jun 15 '17 at 13:08
    for name, layer in layers.iteritems():
        if(layer.name()=="[layer name]"):


    expr = QgsExpression("\"REFCAT\"=22162C50309009")

    expr = QgsExpression(expresion)
    selection= lay.getFeatures(QgsFeatureRequest(expr))
    ids = [s.id() for s in selection]

Is a code used by me, try changing the format of the expression with double quotation marks.

| improve this answer | |

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.