Resetting Stretch To constraints via python

Hi all,
I’m trying to reset all the Stretch To constraints in the selected rig via a python script.
So far I’ve tried this:

import bpy

for bone in bpy.context.selected_pose_bones:
override = bpy.context.copy(bone)
bpy.ops.constraint.stretchto_reset(override, constraint=“Stretch To”, owner=‘BONE’)

which returns the following error:

Traceback (most recent call last):
File “/media/data/glass_half/pre/test_rigs/flexirig-stretchto_fix.blend/Text”, line 5, in <module>
TypeError: copy() takes 1 positional argument but 2 were given

The problem seems to be how I’m using context copy. Any suggestions how I could get this working?

context.copy() does not take any arguments. You can only copy the entire context to a new dict.
If you need to change anything of that context, do it after the copying:

override[“foo”] = “bar”

I wonder if you really need the strechto_reset() operator. It’s often possible to do such things with RNA methods.

So, a little chat with ideasman42 and we have this solution:


import bpy

for b in bpy.context.selected_pose_bones:
    for c in b.constraints: 
        if c.name == "Stretch To":
            c.rest_length = 0

1 Like

Ah so the exposed property just needs to be set to 0…

That’s all the operator does for real:https://developer.blender.org/diffusion/B/browse/master/source/blender/editors/object/object_constraint.c$676

/* just set original length to 0.0, which will cause a reset on next recalc */
data->orglength = 0.0f;

Just wasn’t sure if orglength is exposed or if it’s another internal property. But it’s apparently .rest_length

Yup, that was easier than I thought. Thanks for your help!

hey any way to fix the script to reset every “stretch to” constraint no matter if they’re called stretch to, stretch to.001 or whatever else?

import bpy

for b in bpy.context.selected_pose_bones:
    for c in b.constraints: 
        if c.type == "STRETCH_TO":
            c.rest_length = 0

EDIT: Or you can do…

import bpy

for b in bpy.context.active_object.pose.bones:
    for c in b.constraints: 
        if c.type == "STRETCH_TO":
            c.rest_length = 0

That resets all the stretch to’s in the selected armature, even if they’re not selected, or on an off layer.

2 Likes