Properly registering a custom driver function

solved

(guy lateur) #1

Just in case anyone was wondering: this is a good (the intended?) way to extend the Blender driver namespace with a custom function. It appears that the driver (Scripted Expression) will not work if you just add your function to the namespace in the register() function of your script – this is assuming that your driver script is located in the scripts startup folder, btw.

You need to add the load_post handler if you want this to work straight away after loading a .blend file that uses the custom driver – ie, as you would expect. I think this solution was proposed by batFinger somewhere (not on BA). Anyway, I was going to ask this very question, but I found the answer before I got around to it, so I thought I’d share it here… :slight_smile:

import bpy
from bpy.app.handlers import persistent

def test_driver(val):
    return val * 0.1

@persistent
def load_handler(dummy):
    bpy.app.driver_namespace['test_driver'] = test_driver

def register():
    print("--", "register:", __file__)

    load_handler(None)
    bpy.app.handlers.load_post.append(load_handler)

def unregister():
    bpy.app.handlers.load_post.remove(load_handler)
        
if __name__ == "__main__":
    register()