Skip to content

Commit 773138c

Browse files
committed
Add handlesnull parameter to @qgsfunction
Up to date it was not possible to create a function that handles NULL values with the @qgsfunction decorator. As soon as any parameter was NULL, the return value would also be NULL. Example of a function that returns a value now with a NULL paramter and would have returned NULL before ``` @qgsfunction(args=-1, group='Custom', handlesnull=True) def mean_value(vals, feature, parent): valid_vals = [val for val in vals if val != NULL] return sum(valid_vals)/len(valid_vals) ``` [FEATURE]
1 parent 7b751cb commit 773138c

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

python/core/additions/qgsfunction.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727

2828
def register_function(function, arg_count, group, usesgeometry=False,
29-
referenced_columns=[QgsFeatureRequest.ALL_ATTRIBUTES], **kwargs):
29+
referenced_columns=[QgsFeatureRequest.ALL_ATTRIBUTES], handlesnull=False, **kwargs):
3030
"""
3131
Register a Python function to be used as a expression function.
3232
@@ -51,18 +51,20 @@ def myfunc(values, *args):
5151
:param arg_count:
5252
:param group:
5353
:param usesgeometry:
54+
:param handlesnull:
5455
:return:
5556
"""
5657

5758
class QgsPyExpressionFunction(QgsExpressionFunction):
5859

5960
def __init__(self, func, name, args, group, helptext='', usesGeometry=True,
60-
referencedColumns=QgsFeatureRequest.ALL_ATTRIBUTES, expandargs=False):
61+
referencedColumns=QgsFeatureRequest.ALL_ATTRIBUTES, expandargs=False, handlesNull=False):
6162
QgsExpressionFunction.__init__(self, name, args, group, helptext)
6263
self.function = func
6364
self.expandargs = expandargs
6465
self.uses_geometry = usesGeometry
6566
self.referenced_columns = referencedColumns
67+
self.handles_null = handlesNull
6668

6769
def func(self, values, context, parent, node):
6870
feature = None
@@ -90,6 +92,9 @@ def usesGeometry(self, node):
9092
def referencedColumns(self, node):
9193
return self.referenced_columns
9294

95+
def handlesNull(self):
96+
return self.handles_null
97+
9398
helptemplate = string.Template("""<h3>$name function</h3><br>$doc""")
9499
name = kwargs.get('name', function.__name__)
95100
helptext = kwargs.get('helpText') or function.__doc__ or ''
@@ -119,7 +124,7 @@ def referencedColumns(self, node):
119124
function.__name__ = name
120125
helptext = helptemplate.safe_substitute(name=name, doc=helptext)
121126
f = QgsPyExpressionFunction(function, name, arg_count, group, helptext, usesgeometry, referenced_columns,
122-
expandargs)
127+
expandargs, handlesnull)
123128

124129
# This doesn't really make any sense here but does when used from a decorator context
125130
# so it can stay.

0 commit comments

Comments
 (0)