"'Context' object has no attribute 'active_object'" error when trying to use function as driver import bpy

def driver_func(val):
    activeobj = bpy.context.active_object

    if activeobj.name == "A":
        output = val * val
    else:
        output = val + 20

    return output

#add function to driver_namespace
bpy.app.driver_namespace['driver_func'] = driver_func


Thanks to RJG for the improvement.
This script indeed runs in the scripting editor without errors, but when I
add driver_func in the driver's editor as scripted expression to an object's transform (e.g. z-rotation) I get ERROR: Invalid Python Expression ...

The terminal message reads:

Traceback (most recent call last):
   File "&lt;bpy driver&gt;", line 1, in &lt;module&gt;
   File "/Users/.../Test.blend/TestPython", line 4, in driver_func
AttributeError: 'Context' object has no attribute 'active_object'
You could enable Use Self in the driver editor to get access to the object that the driver is used on. Then you would need to modify the arguments passed into function and use self to check for the name instead of trying to get the active object. The modified script look like this:

import bpy

def driver_func(self, val):
    if self.name == "A":
        output = val * val
    else:
        output = val + 20

    return output

#add function to driver_namespace
bpy.app.driver_namespace['driver_func'] = driver_func


Modify the expression to driver_func(self, var) or replace var with whatever your variable is called. Be aware that your current script increases the value very quickly.



I'm not an expert at Blender's drivers, so if somebody more experienced has a better solution, feel free to add another answer.



Alternatively you can access the active object through bpy.context.view_layer.objects.active as you've pointed out in the comments. Then the script would look like this:

import bpy

def driver_func(val):
    active_obj = bpy.context.view_layer.objects.active

    if active_obj.name == "A":
        output = val * val
    else:
        output = val + 20

    return output

#add function to driver_namespace
bpy.app.driver_namespace['driver_func'] = driver_func