Set driver variable ID-block using python I am trying to build up a scene using python to copy objects and their drivers. The object to copy is a simple cube which has the Custom Property prop and a driver for its x-location. The driver consists of a Scripted Expression which references to the variable var, which is just the Single Property prop of the cube. So when I change the value of the Custom Property prop of the cube, I change its x-location.

To copy this cube, I wrote the following python script:

import bpy

def main():
    scn = bpy.context.scene
    cube = bpy.data.scenes['Scene'].objects['Cube']
    copy_loc_x = 2
    copy_obj(scn, cube, copy_loc_x)

def copy_obj(scn, obj, prop):
    # copy object and set a custom property
    copy = obj.copy()
    copy.data = obj.data.copy()
    copy['prop'] = prop
    scn.objects.link(copy)

if __name__ == '__main__':
    main()


This works perfectly to copy the object and set a new property for the copy, but the copy remains at the same x-location as the original cube. The reason for this is that the variable var of the copy still references to the Custom Property prop of the original cube.

How do I copy the cube, so that its driver variable is automatically referenced to its own Custom Property, just as Shift-D would do? Or, if this is not possible, how do I set the ID-block of a driver variable using python?
Assuming you only have one driver, and that one driver has only one variable, you can do this. after copying the object data:

copy.animation_data.drivers[0].driver.variables[0].targets[0].id = copy


If you have additional drivers and / or variables, you'll need to find better logic to access these. If you can upload a blend file, it will be easier to tell what the best method is.