Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Python Scripting

Blender Python (bpy) Basics: Console, Text Editor, Data API

Start scripting Blender with Python: use the Python Console and Text Editor, explore bpy.data, bpy.context and bpy.ops, and read object properties safely.

Everything you can do with the mouse in Blender can be done with Python, and much more can be automated: placing 500 objects, renaming materials, batch-exporting files or building your own tools. Blender embeds a Python interpreter and exposes its internals through a module named bpy.

Blender is not available on this site, so the Blender-specific code in this lesson is read-only. Where possible we give you a runnable stand-in: a tiny mock of the bpy data model written in plain Python, so you can practice the patterns (looping over objects, reading properties, filtering by name) in the browser. The real bpy behaves like the mock only in the parts we copy, and we say so.

Where to run Python in Blender

  • Python Console: switch an editor to Python Console or use the Scripting workspace. It is an interactive prompt (>>>). Press Tab for autocomplete, which is the best way to discover the API.
  • Text Editor: write, load and run scripts. Press Run Script (or Alt+P) with the cursor in the editor. Output of print() goes to the system console (Window > Toggle System Console on Windows; start Blender from a terminal on macOS and Linux).
  • Info editor: shows the Python call for every action you do in the UI. Do something with the mouse and copy the line. It is the quickest way to learn operator names.

The structure of bpy

Module What it is
bpy.data All data in the open file: objects, meshes, materials, scenes, collections, images, actions
bpy.context The current state: active object, selected objects, current scene, mode
bpy.ops Operators: the same commands as menu items, such as bpy.ops.mesh.primitive_cube_add()
bpy.types The classes (Object, Mesh, Operator, Panel, ...)
bpy.props Property definitions for add-ons
bpy.app, bpy.utils, bpy.path Version info, helpers, paths

A simple script that prints the scene contents (read-only, for Blender):

Python
import bpy

print("Blender version:", bpy.app.version_string)
for obj in bpy.data.objects:
    print(obj.name, obj.type, tuple(obj.location))

bpy.data.objects is a collection you can iterate, index by name (bpy.data.objects["Cube"]) and .get() (returns None if it does not exist).

Reading and changing properties

Each object has properties you can read and set:

Python
import bpy

obj = bpy.context.active_object        # None if nothing is active
if obj is None:
    raise SystemExit("Select an object first")

print(obj.name)                         # "Cube"
print(obj.location)                     # <Vector (0.0000, 0.0000, 0.0000)>
obj.location.z += 2.0                   # move up 2 units
obj.rotation_euler.x = 0.7854           # radians (45 degrees)
obj.scale = (2, 2, 2)
obj.name = "Crate"

Angles are in radians. Use math.radians(45). Colors are (r, g, b, a) tuples from 0 to 1. Rotation mode matters: rotation_euler is for the default Euler mode, rotation_quaternion for quaternion objects.

Tip: right-click any field in the UI and choose Copy Data Path to see the Python path, such as bpy.data.objects["Cube"].location.

A runnable stand-in: practice with a mock scene

The next block builds a tiny pretend bpy.data. It is not Blender, only plain Python with the same shapes, so you can practice loops and filters.

Python Stand-in: a mock scene to practice the bpy patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Operators versus data API

There are two ways to make a change.

Operators (bpy.ops) do what a menu item does and depend on context (mode, area, selection):

Python
import bpy
bpy.ops.mesh.primitive_uv_sphere_add(radius=1.0, location=(0, 0, 2))
bpy.ops.object.shade_smooth()           # applies to selected objects

An operator can fail with RuntimeError: Operator bpy.ops... poll() failed, context is incorrect, for example when you call an Edit Mode operator in Object Mode. Operators also change the selection and the active object.

Data API calls (bpy.data) change data directly, with no context, so they are more reliable and much faster in loops:

Python
import bpy
mesh = bpy.data.meshes.new("MyMesh")
obj = bpy.data.objects.new("MyObject", mesh)
bpy.context.collection.objects.link(obj)    # nothing is visible until you link it

Rule of thumb: use the data API in scripts and add-ons; use bpy.ops for quick one-offs and for things only operators can do (booleans on selection, import and export, baking).

Selection and the active object

Python
import bpy

for obj in bpy.context.selected_objects:
    print("selected:", obj.name)

bpy.ops.object.select_all(action='DESELECT')
cube = bpy.data.objects["Cube"]
cube.select_set(True)
bpy.context.view_layer.objects.active = cube

select_set and view_layer.objects.active are the modern way (older Blender 2.7x code used obj.select = True, which no longer works).

A second runnable stand-in: names and numbering

Blender names duplicates with suffixes like Cube.001. A script often needs to rename in bulk or generate unique names. This stand-in implements the same naming rule.

Python Stand-in: unique names like Blender's Cube.001

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Safe habits

  • Test scripts on a copy of your file; many operations are not easily undone from a script (though Ctrl+Z still works for operator-based changes).
  • Check obj is not None and obj.type == 'MESH' before using mesh properties.
  • Do not run scripts from unknown sources: a script has full access to your files. Blender asks before auto-running scripts in downloaded .blend files; keep that on.
  • Python version and API change with Blender releases. Look at the Python API reference for your version and check "API Changes" notes when old code breaks.
flowchart LR
  UI["Mouse and menus"] --> OP["bpy.ops"]
  SC["Your script"] --> OP
  SC --> DA["bpy.data"]
  CT["bpy.context"] --> SC
  OP --> DB[("Blend file data")]
  DA --> DB

Scripts can use operators or the data API; both change the same data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which part of bpy holds every object, mesh and material in the file?

    bpy.data is the database of the open file. bpy.context is the current state and bpy.ops holds operators.
  2. 2. A script rotates an object with obj.rotation_euler.x = 90. Why is the result wrong?

    Use math.radians(90) for a 90 degree rotation.
  3. 3. Why is the data API preferred over operators in add-ons?

    Operators need a valid context and may fail; the data API changes data directly and is faster.
  4. 4. What does bpy.data.objects.get('Sphere') return when there is no such object?

    get returns None, while indexing with brackets raises a KeyError.

Summary

  • Python runs in the Python Console, the Text Editor and add-ons; the Info editor shows the code for UI actions.
  • bpy.data is the file's data, bpy.context the current state, bpy.ops the menu commands.
  • Angles are radians; use get for safe lookups.
  • Prefer the data API in scripts; use operators where needed.

Next: Creating Objects and Meshes with Scripts