This document isn't intended to fully cover each topic. Rather, its purpose is to familiarize you with Blender 2.5's new Python API.
A quick list of helpful things to know before starting:
* Blender uses Python 3.x; some 3rd party extensions are not available yet.
* The interactive console in Blender 2.5 has been improved; testing one-liners in the console is a good way to learn.
* Button tool tips show Python attributes and operator names.
* Right clicking on buttons and menu items directly links to API documentation.
* For more examples, the text menu has a templates section where some example operators can be found.
* To examine further scripts distributed with Blender, see ``~/.blender/scripts/startup/bl_ui`` for the user interface and ``~/.blender/scripts/startup/bl_op`` for operators.
Python accesses Blender's data in the same way as the animation system and user interface, which means any setting that is changed via a button can also be changed from Python.
Accessing data from the currently loaded blend file is done with the module :mod:`bpy.data`. This gives access to library data. For example:
Once you have a data block such as a material, object, groups etc. its attributes can be accessed just like changing a setting in the interface; in fact, the button tooltip also displays the Python attribute which can help in finding what settings to change in a script.
>>> bpy.data.objects[0].name
'Camera'
>>> bpy.data.scenes["Scene"]
bpy.data.scenes['Scene']
>>> bpy.data.materials.new("MyMaterial")
bpy.data.materials['MyMaterial']
For testing what data to access it's useful to use the "Console", which is its own space type in Blender 2.5. This supports auto-complete, giving you a fast way to dig into different data in your file.
Example of a data path that can be quickly found via the console:
Python can access properties on any datablock that has an ID (data that can be linked in and accessed from :mod:`bpy.data`. When assigning a property, you can make up your own names, these will be created when needed or overwritten if they exist.
This data is saved with the blend file and copied with objects.
Example:
..code-block:: python
bpy.context.object["MyOwnProperty"] = 42
if "SomeProp" in bpy.context.object:
print("Property found")
# Use the get function like a python dictionary
# which can have a fallback value.
value = bpy.data.scenes["Scene"].get("test_prop", "fallback value")
# dictionaries can be assigned as long as they only use basic types.
While it's useful to be able to access data directly by name or as a list, it's more common to operate on the user's selection. The context is always available from '''bpy.context''' and can be used to get the active object, scene, tool settings along with many other attributes.
Common-use cases:
>>> bpy.context.object
>>> bpy.context.selected_objects
>>> bpy.context.visible_bones
Note that the context is read-only. These values cannot be modified directly, though they may be changed by running API functions or by using the data API.
So ``bpy.context.object = obj`` will raise an error.
But ``bpy.context.scene.objects.active = obj`` will work as expected.
The context attributes change depending on where it is accessed. The 3D view has different context members to the Console, so take care when accessing context attributes that the user state is known.
Operators are tools generally accessed by the user from buttons, menu items or key shortcuts. From the user perspective they are a tool but Python can run these with its own settings through the :mod:`bpy.ops` module.
Examples:
>>> bpy.ops.mesh.flip_normals()
{'FINISHED'}
>>> bpy.ops.mesh.hide(unselected=False)
{'FINISHED'}
>>> bpy.ops.object.scale_apply()
{'FINISHED'}
..note::
The menu item: Help -> Operator Cheat Sheet" gives a list of all operators and their default values in Python syntax, along with the generated docs. This is a good way to get an overview of all blender's operators.
Many operators have a "poll" function which may check that the mouse is a valid area or that the object is in the correct mode (Edit Mode, Weight Paint etc). When an operator's poll function fails within python, an exception is raised.
For example, calling bpy.ops.view3d.render_border() from the console raises the following error:
..code-block:: python
RuntimeError: Operator bpy.ops.view3d.render_border.poll() failed, context is incorrect
In this case the context must be the 3d view with an active camera.
To avoid using try/except clauses wherever operators are called you can call the operators own .poll() function to check if it can run in the current context.
Used for vectors, quaternion, eulers, matrix and color types, accessible from :mod:`mathutils`
Some attributes such as :class:`bpy.types.Object.location`, :class:`bpy.types.PoseBone.rotation_euler` and :class:`bpy.types.Scene.cursor_location` can be accessed as special math types which can be used together and manipulated in various useful ways.
The first is through key properties directly, which is similar to inserting a keyframe from the button as a user. You can also manually create the curves and keyframe data, then set the path to the property. Here are examples of both methods.
Both examples insert a keyframe on the active object's Z axis.
For Blender 2.5 we have chosen to follow python suggested style guide to avoid mixing styles amongst our own scripts and make it easier to use python scripts from other projects.
Using our style guide for your own scripts makes it easier if you eventually want to contribute them to blender.
This style guide is known as pep8 and can be found `here <http://www.python.org/dev/peps/pep-0008>`_
A brief listing of pep8 criteria.
* camel caps for class names: MyClass
* all lower case underscore separated module names: my_module
* indentation of 4 spaces (no tabs)
* spaces around operators. ``1 + 1``, not ``1+1``
* only use explicit imports, (no importing '*')
* don't use single line: ``if val: body``, separate onto 2 lines instead.
As well as pep8 we have other conventions used for blender python scripts.
* Use single quotes for enums, and double quotes for strings.
Both are of course strings but in our internal API enums are unique items from a limited set. eg.
* pep8 also defines that lines should not exceed 79 characters, we felt this is too restrictive so this is optional per script.
Periodically we run checks for pep8 compliance on blender scripts, for scripts to be included in this check add this line as a comment at the top of the script.