Constraint bone targets w/ python

I’m trying to create a customized dynamic parenting script. I found this one, but I wanted to hard code some things.
Basically I’m trying to edit it so it toggles the parenting for IK for arms between the chest and root. It is accomplished with “Child of” constraints. Anyway, to the issue:

The original script requires you to select the child bone and the parent bone that you want to create the relationship out of. I want to make it so it happens automatically, and the constraint target is set automatically.

I want:


But I’m getting:

My code:

pose_bones = bpy.context.active_object.pose.bones
parent_obj_pbone = pose_bones[“Root”]
bpy.ops.pose.constraint_add_with_targets(type=‘CHILD_OF’)
last_constraint.subtarget = parent_obj_pbone.
last_constraint.name = “C_”+last_constraint.target.name+"."+last_constraint.subtarget
C = bpy.context.copy()
C[“constraint”] = last_constraint
bpy.ops.constraint.childof_set_inverse(C, constraint=last_constraint.name, owner=‘BONE’)

~~The issue also persists if I select like this: parent_obj_pbone = pose_bones.get(“chest”)

I just want the bone target to appear in the child of constraint, please help!

Ignore the key/drivers in the images

The Bone option will only appear after you select an armature as constraint.target. You’re trying to set the sub target before the target which will not work.