To execute an operator from a context that was not intended for it correctly, it is necessary to override the context for it using bpy.context.temp_override.() selected objects. However, using temp_override, we can override not only the context of the operator call, but also, for example, the stack of selected objects.
A list of all selected objects is stored in the bpy.context.selected_objects.
1 2 3 |
bpy.context.selected_objects # [bpy.data.objects['Cube']] |
If we call the transform.translate() operator
1 |
bpy.ops.transform.translate(value=(0, 1.0, 0), orient_axis_ortho='X', orient_type='GLOBAL') |
all selected objects will move along the global X-axis.
We can use the same transform.translate() operator to move the objects we need, rather than the selected ones. To do this, before calling the operator, let’s temporarily override the list of selected objects.
Define a list with required objects:
1 |
objects = [bpy.data.objects['Suzanne'], bpy.data.objects['Suzanne.001']] |
And use the temp_override() function to override the list of selected objects, specifying the list we created.
1 |
with bpy.context.temp_override(selected_objects=objects): |
Now we can call the transform.translate() operator again
1 |
bpy.ops.transform.translate(value=(0, 1.0, 0), orient_axis_ortho='X', orient_type='GLOBAL') |
As a result of its execution, not the selected objects will be moved, but only those that we specified in our list.
The full code:
1 2 3 4 5 |
import bpy objects = [bpy.data.objects['Suzanne'], bpy.data.objects['Suzanne.001']] with bpy.context.temp_override(selected_objects=objects): bpy.ops.transform.translate(value=(0, 1.0, 0), orient_axis_ortho='X', orient_type='GLOBAL') |
How would you approach context overriding, to enter into edit mode and edit a mesh with the bmesh module? For example, extruding a plane? I used 8 or so arguments in the override, but still it didn’t show as though edit mode had been entered into.
with bpy.context.temp_override(mode=’EDIT_MESH’,
area=area,
active_object=[plane, plane.data],
object=[plane, plane.data],
objects_in_mode=[plane, plane.data],
objects_in_mode_unique_data=[plane, plane.data],
editable_objects=[plane, plane.data],
selected_editable_objects=[plane, plane.data],
selected_objects=[plane, plane.data]):
where plane is an object, plane.data is the mesh.
From where do you know that object/edit mode could be overridden? I’m not sure that this mode could override.
I suppose because it’s in bpy.context, as bpy.context.mode. I was trying to test it by printing what the mode was within the override context management, and made it work once, but don’t seem to be able to repeat it or know if it really is possible at all.
This property is read-only, so, I think this is only flag. We can’t change the object/edit mode just with changing this property thus I think overriding is not works for it.