Sub topic 17
Transforming objects with Python
This chapter assumes you can select objects, use G, R, and S, read the Transform panel, and know what an object origin is. It also assumes you have written a few lines of Python. Everything here runs in Blender's Scripting workspace (Text Editor, then Run Script) or in the Python Console.
The working model
Every object in the scene is a data block stored in bpy.data.objects. The Transform panel is a view onto three properties of that block:
location: a vector of three floats, in scene units.rotation_euler: three angles in radians, not degrees.scale: a vector of three floats, where 1.0 means unscaled.
Setting these properties changes the object directly. Nothing else needs to happen, and no object needs to be selected. This is the main design choice to understand: Python has two ways to act on objects, and they behave differently.
| Approach | Example | Needs selection or context? | Notes |
|---|---|---|---|
| Data API | `obj.location = (1, 2, 3)` | No | Direct, fast, predictable |
| Operators | `bpy.ops.transform.translate(...)` | Often yes | Mimics a menu or shortcut action; depends on context |
Prefer the data API for transforms. Use operators only for actions that have no simple property equivalent, such as applying transforms.
Reading a transform
Start by reading the values of the active object. They match what the Transform panel shows, except that rotation is in radians.
import bpy
obj = bpy.context.active_object
print(obj.name, obj.location, obj.rotation_euler, obj.scale)If nothing is active, obj is None and the print call raises an AttributeError. Check for that in any script you plan to reuse.
The printed values appear in the system console, or in the Python Console if you ran the lines there. To see output from a script run in the Text Editor, open Window > Toggle System Console on Windows, or start Blender from a terminal on macOS and Linux.
Setting location, rotation, and scale
Assign a tuple (or any three-number sequence) to each property.
import bpy
import math
obj = bpy.context.active_object
obj.location = (1.0, 2.0, 0.5)
obj.rotation_euler = (0.0, 0.0, math.radians(45))
obj.scale = (2.0, 2.0, 2.0)This moves the object to (1, 2, 0.5), rotates it 45 degrees around Z, and doubles its size on every axis. These are absolute values, like typing into the Transform panel. They are not relative, like pressing G and moving the mouse.
Radians
Angles in the API are radians. Passing 45 rotates the object by 45 radians, which is about 2578 degrees. Convert with math.radians() when you think in degrees, and with math.degrees() when you want to print a readable value.
Relative changes
To move an object by an offset, read the current value and add to it. Assigning a new value is simpler than modifying components in place, and it also makes the change visible to Blender's update system.
import bpy
from mathutils import Vector
obj = bpy.context.active_object
obj.location = obj.location + Vector((0.0, 0.0, 1.0))You can also write obj.location.z += 1.0. Both work. The vector returned by obj.location is a live reference to the object's data, so component assignment changes the object.
A related gotcha: obj.location is a reference, not a copy. If you store it and later change the object, the stored vector changes too.
import bpy
obj = bpy.context.active_object
start = obj.location.copy() # a snapshot
obj.location.x += 5.0
print(start, obj.location) # start keeps the old valueWithout .copy(), start and obj.location would show the same value.
Rotation modes
rotation_euler is only used when the object's rotation_mode is an Euler mode such as 'XYZ', which is the default. If an object uses quaternion or axis-angle rotation, setting rotation_euler stores values but does not visibly rotate the object. Check the mode first:
import bpy
obj = bpy.context.active_object
print(obj.rotation_mode) # 'XYZ' for most objects
obj.rotation_mode = 'XYZ' # force Euler rotation if neededEuler angles apply in the order named by the mode. In 'XYZ', X is applied first, then Y, then Z, which is why the same three numbers can give different results under 'ZXY'.
Selecting objects from a script
Selection state is stored per view layer. Two separate ideas matter, matching the earlier chapters: whether an object is selected, and which object is active.
import bpy
bpy.ops.object.select_all(action='DESELECT')
obj = bpy.data.objects.get('Cube')
if obj is not None:
obj.select_set(True)
bpy.context.view_layer.objects.active = objThis deselects everything, then selects the object named Cube and makes it active, which matches clicking it in the viewport. Notes:
bpy.data.objects.get('Cube')returnsNoneif no object has that name. Indexing withbpy.data.objects['Cube']raisesKeyErrorinstead.select_set(True)selects the object but does not make it active. Settingview_layer.objects.activemakes it active but does not select it. A script that needs both must do both.- Object names are case sensitive, and Blender adds suffixes such as
.001when a name is already taken. select_allis an operator and needs a suitable context. It works from the Text Editor in the default setup. In a background run (blender -b), prefer looping over objects and callingselect_set(False).
Working on several objects
Because the data API does not need selection, you can transform any set of objects directly. Loop over bpy.context.selected_objects to act on the current selection, or over bpy.data.objects for everything.
import bpy
for obj in bpy.context.selected_objects:
obj.scale = (0.5, 0.5, 0.5)
obj.location.z += 1.0Each object is changed about its own origin. Unlike pressing S in the viewport with several objects selected, the script does not use a shared pivot point. If you want the effect of scaling around the median point, you must compute that point and move each object yourself.
import bpy
from mathutils import Vector
objs = bpy.context.selected_objects
if objs:
pivot = sum((o.location for o in objs), Vector()) / len(objs)
factor = 2.0
for o in objs:
o.location = pivot + (o.location - pivot) * factor
o.scale = o.scale * factorThis reproduces S with the pivot point set to Median Point and the objects scaled by 2. The multiplication of o.scale by a float is supported by Vector.
Parenting and world space
location, rotation_euler, and scale are relative to the object's parent, or to the world if there is no parent. Moving a child by setting location therefore moves it in its parent's space. To read an object's world position, use the world matrix:
import bpy
obj = bpy.context.active_object
print(obj.location) # local to parent
print(obj.matrix_world.translation) # position in the worldmatrix_world is a read-oriented 4x4 matrix. You can assign to it, but the result depends on parenting and on when the dependency graph updates, so assign to the three basic properties when you can.
Applying transforms
Applying has no property equivalent, so use the operator. It does the same as Object > Apply > Rotation & Scale (Ctrl+A), baking the values into the mesh data and resetting those properties to identity (rotation 0, scale 1).
import bpy
obj = bpy.context.active_object
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)The operator acts on the selected objects, and it will fail with a context error if the active object is not in Object Mode or if nothing is selected. It also refuses to apply to multi-user data (a mesh shared by several objects) unless you make the data single-user first.
Clearing a transform is simpler. Setting values by hand does the same job as Alt+G, Alt+R, and Alt+S:
import bpy
obj = bpy.context.active_object
obj.location = (0.0, 0.0, 0.0)
obj.rotation_euler = (0.0, 0.0, 0.0)
obj.scale = (1.0, 1.0, 1.0)Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError: 'NoneType' object has no attribute 'location'` | No active object | Select an object, or set `view_layer.objects.active` |
| Object spins wildly | Degrees passed where radians are expected | Use `math.radians()` |
| Rotation values change but the object does not rotate | `rotation_mode` is not Euler | Check `obj.rotation_mode` |
| Saved vector changes later | Stored a reference | Use `.copy()` |
| `RuntimeError: Operator ... poll() failed, context is incorrect` | Operator run in the wrong mode or area | Switch to Object Mode, or use the data API |
| Child object ends up in an unexpected place | `location` is relative to the parent | Use `matrix_world` to read world position |
Exercises
Exercise
You run obj.rotation_euler = (0, 0, 90) and the object ends up at an odd angle instead of a quarter turn. What went wrong, and what is the corrected line?
Show answer
The API expects radians, so 90 means 90 radians. Use obj.rotation_euler = (0, 0, math.radians(90)) after import math.
Exercise
A script calls obj.select_set(True) on an object and then runs bpy.ops.object.transform_apply(location=False, rotation=True, scale=True). The operator reports a context error. What is likely missing, and how do you add it?
Show answer
The object is selected but not active. Set bpy.context.view_layer.objects.active = obj before calling the operator.
Exercise
Write a short script that moves every selected object up by 2 units on Z without using any operator.
Show answer
import bpy for obj in bpy.context.selected_objects: obj.location.z += 2.0