Override the context.
Another option other than setting the active object is to send an alternative (overridden) context to the operator.
Have used normal blender practice of using the active object to be the target, and add and bind modifier to other mesh objects selected.
Have named the modifier "Foo" to emphasize the use of the reference and not rely on the modifier having the name suggested. Relying on it having name given is a common way to have blender scripts not work as expected because of the naming convention requiring a unique name, that only the first can have.
import bpy
context = bpy.context
target = context.active_object
obs = [o for o in context.selected_objects
if o.type == 'MESH'
and o is not target]
for ob in obs:
mod = ob.modifiers.new("Foo", 'SURFACE_DEFORM')
mod.target = target
bpy.ops.object.surfacedeform_bind(
{"object" : ob},
modifier=mod.name
)
From Blender 3.2+ temp_override
method is introduced.
Which looks like this:
for ob in obs:
mod = ob.modifiers.new("Foo", 'SURFACE_DEFORM')
mod.target = target
with bpy.context.temp_override(object=obj):
bpy.ops.object.surfacedeform_bind(
modifier=mod.name
)
Finally In as much as aligning equals signs is "nicey nicey" and nostalgic for anyone who remembers COBOL
, blender recommends the usage of PEP8 for formatting code. If your addon makes the repo it will be cleaned away by autopep8