Add new expressions to existing scripted expressions in driver?

I’m making a script that will allow me to set up an emotion using shapekeys on my character, then shift select the bone I want to control it with and run the script to hook it up to that bone. It works fine with only one emotion, but when I try to add the next emotion the expression is overwritten so only the last emotion/bone works.

It’s pretty obvious because I’m setting (and overwriting) the expression with
driver.driver.expression = str(value) +"*" + var.name
where var.name is the name of the bone selected and value is the value of the shapekey. Basically the script loops through all of the shapekeys and gets the value and sets that as a multiplier for the expression.

I would like to add the next bone to the expression instead of replacing it, so for example "0.5emotion_a" would be "0.5emotion_a + 1*emotion_b). Is this possible?

I would also want to replace the expression of existing bones so I could update expressions, so if I had “0.5emotion_a + 1emotion_b” and ran the script again on the emotion_b bone but with changed values it would become “0.5emotion_a + 0.75emotion_b” instead of adding another emotion_b to the expression.

I’m grateful for any help. :cool:

I managed to solve this myself. The problem was that Blender overwrites the value of the expression each time the driver is created when calling driver_add(). Instead I get the old value from the driver in animation_data before creating the new driver and save that as a string. Then I split the string by “+”, check each string if it ends with the pose bone name, and if it does, I replace the value rather than adding it again. Finally I set the expression to the new string (after adding the pieces of strings back together).