Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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]
  • Loading branch information
m-kuhn committed Jun 30, 2018
1 parent 7b751cb commit 773138c
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions python/core/additions/qgsfunction.py
Expand Up @@ -26,7 +26,7 @@


def register_function(function, arg_count, group, usesgeometry=False,
referenced_columns=[QgsFeatureRequest.ALL_ATTRIBUTES], **kwargs):
referenced_columns=[QgsFeatureRequest.ALL_ATTRIBUTES], handlesnull=False, **kwargs):
"""
Register a Python function to be used as a expression function.
Expand All @@ -51,18 +51,20 @@ def myfunc(values, *args):
:param arg_count:
:param group:
:param usesgeometry:
:param handlesnull:
:return:
"""

class QgsPyExpressionFunction(QgsExpressionFunction):

def __init__(self, func, name, args, group, helptext='', usesGeometry=True,
referencedColumns=QgsFeatureRequest.ALL_ATTRIBUTES, expandargs=False):
referencedColumns=QgsFeatureRequest.ALL_ATTRIBUTES, expandargs=False, handlesNull=False):
QgsExpressionFunction.__init__(self, name, args, group, helptext)
self.function = func
self.expandargs = expandargs
self.uses_geometry = usesGeometry
self.referenced_columns = referencedColumns
self.handles_null = handlesNull

def func(self, values, context, parent, node):
feature = None
Expand Down Expand Up @@ -90,6 +92,9 @@ def usesGeometry(self, node):
def referencedColumns(self, node):
return self.referenced_columns

def handlesNull(self):
return self.handles_null

helptemplate = string.Template("""<h3>$name function</h3><br>$doc""")
name = kwargs.get('name', function.__name__)
helptext = kwargs.get('helpText') or function.__doc__ or ''
Expand Down Expand Up @@ -119,7 +124,7 @@ def referencedColumns(self, node):
function.__name__ = name
helptext = helptemplate.safe_substitute(name=name, doc=helptext)
f = QgsPyExpressionFunction(function, name, arg_count, group, helptext, usesgeometry, referenced_columns,
expandargs)
expandargs, handlesnull)

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

0 comments on commit 773138c

Please sign in to comment.