9

I created a function force_numeric_list in my QGIS Expression "Function Editor" (see image below) to reuse it in other functions there, e.g. as shown below in the function get_min_from_attributes().

When simply calling the function

force_numeric_list(attrmap_filtered.values(), True)

I get the error:

'QgsPyExpressionFunction' object is not callable.

I've learned here, that this is due to the special circumstance under which the Expression functions are called, needing to have the arguments of feature and parent (however simply passing them with force_numeric_list(..., feature, parent) doesn't work either.

I can however evaluate the function like this

QgsExpression('force_numeric_list(attrmap_filtered.values(), True)').evaluate()

but this returns NULL, which doesn't help (since I need the return value of the function).

How can I call QgsPyExpressionFunctions from within QgsPyExpressionFunctions and get their return values?

using function force_numeric_list in my QGIS Expression "Function Editor"

1 Answer 1

12

The problem is not about feature or parent parameter. It arises because the string in QgsExpression is not a valid QGIS expression.

attrmap_filtered.values() in the expression is a Pythonic syntax, not a valid qgis expression. To pass a Python list to QgsExpression, you can convert the list to a string and wrap it in the array function.

Let force_numeric_list function be:

@qgsfunction(args='auto', group='Custom', referenced_columns=[])
def force_numeric_list(values, feature, parent):
    # multiply the values by 10
    values = [v*10 for v in values]    
    return values

And get_min_from_attributes should be like this:

@qgsfunction(args='auto', group='Custom', referenced_columns=[])
def get_min_from_attributes(feature, parent):

    # sample dictionary
    attrmap_filtered = {"a": 1, "b":2}
    
    ##################
    # convert dict values to joint str to use in 'array' function of expression
    values_as_str = ",".join(map(str, attrmap_filtered.values())) # -> '1,2'
    
    # this string has to be a valid expression string
    expr_str = f'force_numeric_list(array({values_as_str}))'
    # the expression is force_numeric_list(array(1,2))'
    ##################
    
    my_vals = QgsExpression(expr_str).evaluate()

    return my_vals

Result:

enter image description here

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.