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

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():
pass
def saveProject():
pass
def closeProject():
QgsExpression.unregisterFunction('my_sum')
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
.