[GIS] Using list of values for custom function in QGIS Field Calculator

field-calculatorqgisqgis-custom-function

I'm writing a custom function in the Field Calculator (QGIS 2.18.5).

Creating a new function from Function Editor > New file, I'm able to start using a default function called func:

"""
Define new functions using @qgsfunction. feature and parent must always be the
last args. Use args=-1 to pass a list of values as arguments
"""

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def func(value1, feature, parent):
    return value1

At the beginning of the above code, I noticed this:

Use args=-1 to pass a list of values as arguments

Desiring to pass, for example, this list:

my_list = ['a', 'b', 'c']

as an input parameter, I tried to use args=-1 instead of args='auto':

@qgsfunction(args=-1, group='Custom')
def my_func(my_list, feature, parent):
    return my_list

but I wasn't able to add this list for my custom function because I wrote it using an invalid syntax:

enter image description here

What am I doing wrong? Or maybe I made some confusion about the using of args?

Best Answer

After some trial-and-errors, I found a working solution.

For passing a list as an argument, it would be enough setting the length of the list as a value for the args parameter. Then, since a list can't be returned by the function, it is necessary to specify a value from the list.

In my case, I need to rewrite the function in this way:

@qgsfunction(args=3, group='Custom')
def my_func(my_list, feature, parent):
    val = my_list[1]
    return val

and call the function by directly inserting only a list as a parameter:

enter image description here

As desired, the function returns the second value from the list which is directly specified inside the parentheses (without recurring to the square brackets as it is usually done for lists).

Related Question