Is it possible to define a custom Python Expression function like in the project macros?

Each time when I try to enable the macros and write any code, I get a security warning saying that Python macros cannot currently be run (as in the attached pictures).

enter image description here

enter image description here

I get a crash when attempting to run the last screenshot scenario.

  • 1
    On the right of the security warning there is an "Enable Macro" link did you try to click on that ? Also on the QGIS option (General tab) what is the status of the "Enable macros" setting ?
    – J.R
    Nov 29, 2021 at 11:14
  • In the first case ("Hello I am a macro" example) there is an error QgsMessangerBar.INFO . Once I deleted it the macro will work but the warning it will still appear. Whereas in the second case (with that function), the QGIS crashes when I click on "Enable Macro" link. The Enable macros is set to "Ask". Should it be set to "Always"? What I am actually trying to do is to define in the macros a "Custom Python expression function" like to use it in the forms of the project.
    – NEM
    Nov 29, 2021 at 11:52

1 Answer 1


You can create a custom expression function in a macro in this way:

enter image description here

Sample code:

from qgis.utils import qgsfunction
from qgis.core import QgsExpression

@qgsfunction(args='auto', group='test', referenced_columns=[])
def my_sum(value1, value2, feature, parent):
    return value1 + value2

def openProject():

def saveProject():

def closeProject():

Note we unregister the created function when closing the project.

Therefore, the function my_sum() will only be available while your project is open, if the user accepts macros in her/his QGIS session.

Due to security issues that macros could trigger, your users will be asked for confirmation on running your macro, unless they have set the Enable macros option to Always (Not Recommended) in Settings --> Options... --> General.

  • Is the function automatically registered?
    – Noura
    Nov 29, 2021 at 19:57
  • Yes, as soon as QGIS finds the @qgsfunction decorator, QGIS knows that's a function ready to be registered, and proceeds with its registration. Nov 29, 2021 at 20:33
  • Thank you! It works indeed. I did not find this in the documentation. I wonder how you know about it.
    – NEM
    Dec 6, 2021 at 12:26
  • 1
    Well, there are lots of things you know by practicing and by attempting alternate solutions. I've been working with PyQGIS since 2009! So, that's the secret :) Dec 10, 2021 at 0:03

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.