1

I am trying to import a csv layer and run QgsExpression.evaluate() to make some computations on existing columns. However, QGIS 2.18, 3.2, and 3.3 all close when it reaches that point.

    layer.startEditing()

    context = QgsExpressionContext()
    scope = QgsExpressionContextScope()

    exp = QgsExpression(expression)
    if exp.hasParserError():
        raise Exception(exp.parserErrorString())

    for f in layer.getFeatures():
        QApplication.processEvents()
        scope.setFeature(f)
        context.appendScope(scope)

        value = exp.evaluate(context)

        computed_values[field_name].append(value)

        f.setAttribute(f.fieldNameIndex(field_name), value)

        layer.updateFeature(f)

    layer.commitChanges()

Is there any way to make it work for shapefile, or just ogr table layer?

1 Answer 1

2

Don't append the scope inside your loop, do it once outside the loop. Appending the scope transfers ownership of it to the context, and re-appending on the next iteration of the loop will cause undefined behaviour.

0

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.