For operators use context.
Given the self
in the question code, making the assumption you are writing an operator
Further to the answer of @RoufirHassan by way of explanation, looping over the collection objects de-selecting and selecting single, was not changing the active object. Adding context.object
to print statement would confirm this.
Is the active object and zeroth selected object always the same?
to fix set the active object to the loop object before calling operator.
context.view_layer.objects.active = obj
Blender 2.8 API, python, set active object
However an issue here would be scripts have a tendency to slow down horribly if looping a lot of operators. The operator run count using amended question code would be 2 x number of objects in collection.
Modifier add operator adds to the end of modifier stack
if using the modifiers add operator the newly added modifier will be
context.object.modifiers[-1]
ie the last one. Once again in blender using name can be dodgy, just like with objects adding another with same name will not have the same name.
Prime candidate for KeyError
Never use bpy.data.whatevers["Foo"]
unless you are certain "Foo" exists. Where it can have value None
Also recommend using scene objects, as if the object in bpy.data.objects
is not linked to scene it likely wont work as expected.
target = context.scene.objects.get("Foo")
or use the context. In this case for example, the collection can be context collection (last selected in outliner) and the modifier target can be context.object
Overriding context
Can pass a context dictionary to operators. Below is method explained by @RoufirHassan using override. Note: this will add all modifiers of first mesh object in collection (including newly added mirror) to all other mesh objects in collection, except to the mirror target if it is a mesh object in same collection
This will run only 2 operators no matter how many objects are in the collection.
import bpy
context = bpy.context
coll = context.collection
ob = context.object
mesh_obs = [o for o in coll.all_objects
if o.type == 'MESH'
and o is not ob]
if mesh_obs:
ao = mesh_obs.pop(0)
bpy.ops.object.modifier_add(
{"object" : ao},
type='MIRROR'
)
mod = ao.modifiers[-1]
mod.use_axis = (True, False, True)
mod.mirror_object = ob
bpy.ops.object.make_links_data(
{"object" : ao,
"selected_editable_objects": mesh_obs
},
type='MODIFIERS',
)
API methods.
Finally would recommend using the API method as suggested in answer of @Pysonic, except use the context to set collection and modifier target.