Script changes to driver expressions and variables Scripting newb here.

I have thousands of unique objects named plane.001, plane.002 etc. They all unique meshes with a single shapekey apart from the basis. The shapekey has a driver on its evaluation time and the variable type of the driver is distance, with an empty as the first target.

I'm trying to write a script that changes the second target of my distance variable to the same object that contains the driver. Since I simply duplicated the original object thousands of times, they all have the original object as the second target.

I'm hoping someone will throw me a bone here, show me a viable script and explain what's going on. I do have experience with programming languages but I'm very much an amateur.

Thanks a lot lot lot!
import bpy
context = bpy.context
scene = context.scene

for obj in scene.objects:
    mesh = obj.data
    if not mesh or not hasattr(mesh, "shape_keys"):
        continue

    # shape key collection
    shapekeys = mesh.shape_keys

    # animation data
    ad = getattr(shapekeys, "animation_data", None)    
    # no animtion data no drivers
    if not ad:
        continue

    #select the driver part of fcurves in drivers list
    drivers = [fc.driver for fc in ad.drivers]

    for d in drivers:
        #variables of type distance
        vars = [v for v in d.variables if v.type == 'LOC_DIFF']
        for v in vars:
            # set the target 2 to obj that has driver.
            v.targets[1].id = obj