Is it possible to use a variable with default value (value2) defined in a custom Python expression function?

@qgsfunction(args='auto', group='UserFunction')
def my_test(value1, feature, parent, value2=True):
    if value2:
        return 100
        return 0

I know that this question was already asked years ago (Optional variable (with default value) in custom function) but I wonder if there is another way. In Python, the default values are placed at the end. However, if I do that, the second does not change:

mytest(13, True) -> returns 100
mytest(13, False) -> returns 100 
  • 2
    And with handlesnull=True in the decorator, with a value2 arg just after value1 and in the code if value2 is None: value2 = True ? Nov 29, 2021 at 11:06
  • 1
    Thank you J! I know about this workaround but I wonder if there is another way to deal with default parameters.
    – NEM
    Nov 29, 2021 at 11:54
  • 1
    Answer: no, currently there is no way of doing that. The docs say: "Define any parameters you want to pass to your function before the following arguments.", referring to feature, parent and optionally context. That is, feature and parent are mandatory and you cannot place any custom parameter after them (except by context, which is not a custom one). On the other hand, any attempt of placing a custom parameter with default value before the mandatory ones (feature and parent) will throw a Syntax Error from Python: SyntaxError: non-default argument follows default argument. Nov 29, 2021 at 12:32


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.