I would recommend that you use a proper IDE (Integrated Development Environment) that supports Python. This will allow you to check for syntax problems. The correct indentation of the code is important for Python because it is used to determine what part of the code belongs to, e.g. an if, else condition or a function.
Correctly formatted your first code should look like this:
import bpy
def driver_func(val):
if val < 5:
output = val * val
else:
output = val + 20
return output
# add function to driver_namespace
bpy.app.driver_namespace['driver_func'] = driver_func
Note that everything that belong into the function is indented by four spaces. What belongs inside the condition is indent by another four additional spaces. This is necessary in Python, because unlike for instance C, it doesn't use curly braces to determine the scope.
Your second script is problematic for two reasons.
- The syntax is invalid. If you want to perform an equality check you have to use
==
instead of =
. The latter is only used to assign a value to a variable.
- You're declaring a variable outside the function, but are using it inside without passing it as an argument. This is bad because a) you don't want to create global state b) in this particular case the driver will not be able to access the variable because it has gone out of scope. The
bpy.app.driver_namespace['driver_func']
only contains a reference to the function, but not the variable you're trying to use.
- You cannot access the active object like through
bpy.context.active_object
when using the code in a driver. It should be bpy.context.view_layer.objects.active
.
The correct script would therefore be:
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