Sub topic 14
Controlling modes and workspaces with Python
This chapter shows how to read and change the interaction mode and the workspace from a script. It assumes you know what Object Mode, Edit Mode, and workspaces are from the earlier chapters. It also assumes basic Python (functions, if, for, with) and that you can open Blender's Scripting workspace and run a script in the Text Editor.
Where the state lives
A script has to find three pieces of state in Blender's Python API (bpy):
- The object's mode.
obj.modeis a string such as'OBJECT','EDIT','SCULPT','POSE','VERTEX_PAINT','WEIGHT_PAINT', or'TEXTURE_PAINT'. - The active workspace.
bpy.context.window.workspaceholds the workspace shown in the current window. - The workspace's linked mode.
workspace.object_modeis the mode Blender switches to when you activate that workspace.
Mode is stored per object, and the workspace is stored per window. Blender allows only one object mode at a time in a given view layer, so the active object's mode is usually the one that matters.
Reading and changing the mode
The standard way to change mode is the mode_set operator. It does what the mode menu and the Tab key do, including updating the interface and syncing mesh data.
import bpy
obj = bpy.context.active_object
if obj is not None and obj.type == 'MESH':
print(obj.mode) # 'OBJECT' or 'EDIT', and so on
bpy.ops.object.mode_set(mode='EDIT')
print(obj.mode) # 'EDIT'
bpy.ops.object.mode_set(mode='OBJECT')
print(obj.mode) # 'OBJECT'mode_set acts on the active object (view_layer.objects.active), not on a variable you hold. If you have an object obj that isn't active, make it active first. Selecting it is not enough.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `RuntimeError: Operator bpy.ops.object.mode_set.poll() failed, context is incorrect` | No active object, or the active object is hidden, linked from a library, or the wrong type for the mode | Check `obj` for `None`, set it active, unhide it, and check `obj.type` |
| `TypeError: ... enum "POSE" not found` or a similar message | The mode doesn't exist for that object type. For example, `'POSE'` needs an armature and `'EDIT'` needs a type with an edit mode | Pick a mode valid for `obj.type` |
| The script reports `'OBJECT'` right after you asked for another mode | The operator was cancelled, or the object was not active | Print `obj.mode` after the call and check the Info editor for operator errors |
| `mode_set` fails when run from a timer, handler, or add-on callback | The context has no active object or window | Set the active object explicitly, or use `bpy.context.temp_override(...)` |
mode_set also takes a toggle argument. Leave it at its default of False in scripts. A scripted call should say which mode you want, not flip whatever mode is current.
A safe pattern: restore what you changed
Scripts that change mode and don't restore it leave the user in a surprising state. A context manager makes the restore automatic, even if an error is raised inside the block.
import bpy
from contextlib import contextmanager
@contextmanager
def in_mode(obj, mode):
view_layer = bpy.context.view_layer
previous_active = view_layer.objects.active
previous_mode = obj.mode
view_layer.objects.active = obj
if previous_mode != mode:
bpy.ops.object.mode_set(mode=mode)
try:
yield obj
finally:
if obj.mode != previous_mode:
view_layer.objects.active = obj
bpy.ops.object.mode_set(mode=previous_mode)
view_layer.objects.active = previous_active
obj = bpy.context.active_object
if obj is not None and obj.type == 'MESH':
with in_mode(obj, 'EDIT'):
print("Inside the block:", obj.mode)
print("After the block:", obj.mode)Editing mesh data in Edit Mode
In Edit Mode, Blender holds the geometry in a separate editing structure. The regular obj.data.vertices collection is not updated until you leave Edit Mode. If you change obj.data.vertices[i].co while in Edit Mode, the edit may be lost or overwritten when you leave.
Use BMesh for Edit Mode work. bmesh.from_edit_mesh gives you a live view of the geometry being edited, and bmesh.update_edit_mesh tells Blender you changed it.
import bpy
import bmesh
obj = bpy.context.edit_object # None unless a mesh is in Edit Mode
if obj is not None and obj.type == 'MESH':
bm = bmesh.from_edit_mesh(obj.data)
for vert in bm.verts:
if vert.select:
vert.co.z += 1.0
bmesh.update_edit_mesh(obj.data)Do not call bm.free() on a BMesh you got from from_edit_mesh. Blender owns it. Freeing is only for BMesh objects you created with bmesh.new().
Reading edit data from Object Mode code
Sometimes you want to read the edited geometry through obj.data without leaving Edit Mode. obj.update_from_editmode() copies the edit-mode state into the regular mesh data.
import bpy
obj = bpy.context.edit_object
if obj is not None and obj.type == 'MESH':
obj.update_from_editmode()
selected = [v.index for v in obj.data.vertices if v.select]
print("Selected vertex indices:", selected)This is read-only in spirit. Writing to obj.data after the sync does not push changes back into the edit session.
Object-level changes versus data-level changes
The Object Mode versus Edit Mode split from earlier chapters shows up in the API as two different places to write.
import bpy
obj = bpy.context.active_object
if obj is not None and obj.type == 'MESH':
bpy.ops.object.mode_set(mode='OBJECT')
obj.location.x += 2.0 # object-level change (transform)
obj.data.vertices[0].co.z += 1.0 # data-level change (one vertex)obj.location, obj.rotation_euler, and obj.scale are properties of the object. obj.data.vertices[...] belongs to the mesh data. The call to mode_set(mode='OBJECT') is there so that obj.data is current before the script writes to it.
Mesh data can be shared between objects (linked duplicates). Changing obj.data then changes every object that uses it. Check obj.data.users if you need to know.
Selection mode and multi-object editing
The vertex, edge, and face select modes live in the tool settings, not on the object. The value is a tuple of three booleans, in the order vertex, edge, face.
import bpy
ts = bpy.context.tool_settings
ts.mesh_select_mode = (False, False, True) # face select
print(tuple(ts.mesh_select_mode))Setting the tuple changes the mode but does not convert the existing selection the way pressing 1, 2, or 3 in the viewport does. If you want Blender's usual selection conversion, use the operator bpy.ops.mesh.select_mode(type='FACE') while in Edit Mode.
With multi-object editing, several meshes are in Edit Mode together. bpy.context.edit_object gives you only the active one. To reach all of them, use bpy.context.objects_in_mode:
import bpy
import bmesh
for obj in bpy.context.objects_in_mode_unique_data:
if obj.type != 'MESH':
continue
bm = bmesh.from_edit_mesh(obj.data)
count = sum(1 for v in bm.verts if v.select)
print(f"{obj.name}: {count} selected vertices")objects_in_mode_unique_data skips objects that share mesh data, so each mesh is visited once. Use objects_in_mode when you need every object.
To put several objects into Edit Mode from a script, select them, make one active, and call mode_set(mode='EDIT'). Blender brings all selected compatible objects along.
Reading and switching workspaces
Workspaces are stored in bpy.data.workspaces. Setting bpy.context.window.workspace switches the one the current window shows.
import bpy
workspace = bpy.data.workspaces.get("Modeling")
if workspace is not None:
bpy.context.window.workspace = workspace
print([ws.name for ws in bpy.data.workspaces])Two behaviors matter here:
- The switch is deferred. The window changes on the next interface update. Code after the assignment may still see the old
bpy.context.workspace. If later steps depend on the new layout, run them from a timer registered withbpy.app.timers.register. - The linked mode applies. Activating a workspace can also change the mode, based on its
object_modesetting. You can read it and change it:
import bpy
for ws in bpy.data.workspaces:
print(f"{ws.name:<16} -> {ws.object_mode}")
sculpting = bpy.data.workspaces.get("Sculpting")
if sculpting is not None:
sculpting.object_mode = 'SCULPT'If a script switches workspace and then checks obj.mode, the answer can differ from what you set earlier. Treat the workspace's object_mode as part of the state you are changing.
Creating a workspace from a script
The data API doesn't offer a new() for workspaces. The usual route is to duplicate an existing one with an operator and rename the copy. The operator acts on the active workspace.
import bpy
before = {ws.name for ws in bpy.data.workspaces}
bpy.ops.workspace.duplicate()
new_ws = next(ws for ws in bpy.data.workspaces if ws.name not in before)
new_ws.name = "My Modeling"
new_ws.object_mode = 'EDIT'
print("Created:", new_ws.name)Comparing names before and after avoids guessing which workspace is the new one. Layout changes inside the new workspace, such as resizing areas or changing editor types, are done with new_ws.screens and each screen's areas. Changing an area's editor type is a small edit (area.type = 'IMAGE_EDITOR'), but moving the area borders is not well supported from Python. For anything beyond switching and light changes, build the layout by hand, then script around it.
Choosing between API and operators
| Task | Prefer | Why |
|---|---|---|
| Change mode | `bpy.ops.object.mode_set` | It updates the interface and syncs mesh data |
| Move vertices in Edit Mode | `bmesh.from_edit_mesh` | It edits live edit-mode data |
| Move vertices in Object Mode | `obj.data.vertices` or `foreach_set` | It is direct and fast |
| Switch workspace | `window.workspace = ws` | No operator needed |
| Create a workspace | `workspace.duplicate` then rename | No `new()` call exists |
Exercise
A script sets obj.location.x += 2.0 and then obj.data.vertices[0].co.z += 1.0 while the object is in Edit Mode. The vertex change is lost when the user leaves Edit Mode. Why, and what are two valid fixes?
Show answer
In Edit Mode the geometry is held in the editing structure, and obj.data.vertices is not kept in sync with it, so the later write to obj.data is overwritten when Blender writes the edit data back on exit. Fix 1: call bpy.ops.object.mode_set(mode='OBJECT') before changing obj.data.vertices. Fix 2: stay in Edit Mode and edit through BMesh with bmesh.from_edit_mesh(obj.data), then call bmesh.update_edit_mesh(obj.data). The location change is an object-level property and works in either mode.
Exercise
Write the lines that switch to a workspace named "Shading" if it exists, and explain why reading bpy.context.workspace on the next line might still show the old workspace.
Show answer
ws = bpy.data.workspaces.get("Shading") then if ws is not None: bpy.context.window.workspace = ws. The window updates its workspace when the interface next refreshes, after the script returns, so bpy.context.workspace can still return the previous one on the next line. To act after the switch, register a function with bpy.app.timers.register.