5 This document attempts to help you work with the Blender API in areas
6 that can be troublesome and avoid practices that are known to give instability.
14 Blender's operators are tools for users to access, that Python can access them too is very useful
15 nevertheless operators have limitations that can make them cumbersome to script.
19 - Can't pass data such as objects, meshes or materials to operate on (operators use the context instead)
20 - The return value from calling an operator gives the success (if it finished or was canceled),
21 in some cases it would be more logical from an API perspective to return the result of the operation.
22 - Operators poll function can fail where an API function would raise an exception giving details on exactly why.
25 Why does an operator's poll fail?
26 ---------------------------------
28 When calling an operator gives an error like this:
30 >>> bpy.ops.action.clean(threshold=0.001)
31 RuntimeError: Operator bpy.ops.action.clean.poll() failed, context is incorrect
33 Which raises the question as to what the correct context might be?
35 Typically operators check for the active area type, a selection or active object they can operate on,
36 but some operators are more picky about when they run.
38 In most cases you can figure out what context an operator needs
39 simply be seeing how it's used in Blender and thinking about what it does.
42 Unfortunately if you're still stuck - the only way to **really** know
43 whats going on is to read the source code for the poll function and see what its checking.
45 For Python operators it's not so hard to find the source
46 since it's included with Blender and the source file/line is included in the operator reference docs.
48 Downloading and searching the C code isn't so simple,
49 especially if you're not familiar with the C language but by searching the
50 operator name or description you should be able to find the poll function with no knowledge of C.
54 Blender does have the functionality for poll functions to describe why they fail,
55 but its currently not used much, if you're interested to help improve our API
56 feel free to add calls to ``CTX_wm_operator_poll_msg_set`` where its not obvious why poll fails.
58 >>> bpy.ops.gpencil.draw()
59 RuntimeError: Operator bpy.ops.gpencil.draw.poll() Failed to find Grease Pencil data to draw into
62 The operator still doesn't work!
63 --------------------------------
65 Certain operators in Blender are only intended for use in a specific context,
66 some operators for example are only called from the properties window where they check the current material,
67 modifier or constraint.
71 - :mod:`bpy.ops.texture.slot_move`
72 - :mod:`bpy.ops.constraint.limitdistance_reset`
73 - :mod:`bpy.ops.object.modifier_copy`
74 - :mod:`bpy.ops.buttons.file_browse`
76 Another possibility is that you are the first person to attempt to use this operator
77 in a script and some modifications need to be made to the operator to run in a different context,
78 if the operator should logically be able to run but fails when accessed from a script
79 it should be reported to the bug tracker.
86 No updates after setting values
87 -------------------------------
89 Sometimes you want to modify values from Python and immediately access the updated values, eg:
91 Once changing the objects :class:`bpy.types.Object.location`
92 you may want to access its transformation right after from :class:`bpy.types.Object.matrix_world`,
93 but this doesn't work as you might expect.
95 Consider the calculations that might go into working out the object's final transformation, this includes:
97 - animation function curves.
98 - drivers and their Python expressions.
100 - parent objects and all of their f-curves, constraints etc.
102 To avoid expensive recalculations every time a property is modified,
103 Blender defers making the actual calculations until they are needed.
105 However, while the script runs you may want to access the updated values.
106 In this case you need to call :class:`bpy.types.Scene.update` after modifying values, for example:
108 .. code-block:: python
110 bpy.context.object.location = 1, 2, 3
111 bpy.context.scene.update()
114 Now all dependent data (child objects, modifiers, drivers... etc)
115 has been recalculated and is available to the script.
118 Can I redraw during the script?
119 -------------------------------
121 The official answer to this is no, or... *"You don't want to do that"*.
123 To give some background on the topic...
125 While a script executes Blender waits for it to finish and is effectively locked until its done,
126 while in this state Blender won't redraw or respond to user input.
127 Normally this is not such a problem because scripts distributed with Blender
128 tend not to run for an extended period of time,
129 nevertheless scripts *can* take ages to execute and its nice to see whats going on in the view port.
131 Tools that lock Blender in a loop and redraw are highly discouraged
132 since they conflict with Blenders ability to run multiple operators
133 at once and update different parts of the interface as the tool runs.
135 So the solution here is to write a **modal** operator, that is - an operator which defines a modal() function,
136 See the modal operator template in the text editor.
138 Modal operators execute on user input or setup their own timers to run frequently,
139 they can handle the events or pass through to be handled by the keymap or other modal operators.
141 Transform, Painting, Fly-Mode and File-Select are example of a modal operators.
143 Writing modal operators takes more effort than a simple ``for`` loop
144 that happens to redraw but is more flexible and integrates better with Blenders design.
147 **Ok, Ok! I still want to draw from Python**
149 If you insist - yes its possible, but scripts that use this hack wont be considered
150 for inclusion in Blender and any issues with using it wont be considered bugs,
151 this is also not guaranteed to work in future releases.
153 .. code-block:: python
155 bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
158 Modes and Mesh Access
159 =====================
161 When working with mesh data you may run into the problem where a script fails to run as expected in edit-mode.
162 This is caused by edit-mode having its own data which is only written back to the mesh when exiting edit-mode.
164 A common example is that exporters may access a mesh through ``obj.data`` (a :class:`bpy.types.Mesh`)
165 but the user is in edit-mode, where the mesh data is available but out of sync with the edit mesh.
167 In this situation you can...
169 - Exit edit-mode before running the tool.
170 - Explicitly update the mesh by calling :class:`bmesh.types.BMesh.to_mesh`.
171 - Modify the script to support working on the edit-mode data directly, see: :mod:`bmesh.from_edit_mesh`.
172 - Report the context as incorrect and only allow the script to run outside edit-mode.
175 .. _info_gotcha_mesh_faces:
177 NGons and Tessellation Faces
178 ============================
180 Since 2.63 NGons are supported, this adds some complexity
181 since in some cases you need to access triangles/quads still (some exporters for example).
183 There are now 3 ways to access faces:
185 - :class:`bpy.types.MeshPolygon` -
186 this is the data structure which now stores faces in object mode
187 (access as ``mesh.polygons`` rather then ``mesh.faces``).
188 - :class:`bpy.types.MeshTessFace` -
189 the result of triangulating (tessellated) polygons,
190 the main method of face access in 2.62 or older (access as ``mesh.tessfaces``).
191 - :class:`bmesh.types.BMFace` -
192 the polygons as used in editmode.
194 For the purpose of the following documentation,
195 these will be referred to as polygons, tessfaces and bmesh-faces respectively.
197 5+ sided faces will be referred to as ``ngons``.
208 - :class:`bpy.types.MeshPolygon`
209 - :class:`bpy.types.MeshTessFace`
210 - :class:`bmesh.types.BMFace`
212 - Poor *(inflexible)*
213 - Good *(supported as upgrade path)*
216 - Poor *(inflexible)*
217 - Poor *(loses ngons)*
220 - Good *(ngon support)*
221 - Good *(When ngons can't be used)*
222 - Good *(ngons, extra memory overhead)*
226 Using the :mod:`bmesh` api is completely separate api from :mod:`bpy`,
227 typically you would would use one or the other based on the level of editing needed,
228 not simply for a different way to access faces.
234 All 3 datatypes can be used for face creation.
236 - polygons are the most efficient way to create faces but the data structure is _very_ rigid and inflexible,
237 you must have all your vertes and faces ready and create them all at once.
238 This is further complicated by the fact that each polygon does not store its own verts (as with tessfaces),
239 rather they reference an index and size in :class:`bpy.types.Mesh.loops` which are a fixed array too.
240 - tessfaces ideally should not be used for creating faces since they are really only tessellation cache of polygons,
241 however for scripts upgrading from 2.62 this is by far the most straightforward option.
242 This works by creating tessfaces and when finished -
243 they can be converted into polygons by calling :class:`bpy.types.Mesh.update`.
244 The obvious limitation is ngons can't be created this way.
245 - bmesh-faces are most likely the easiest way for new scripts to create faces,
246 since faces can be added one by one and the api has features intended for mesh manipulation.
247 While :class:`bmesh.types.BMesh` uses more memory it can be managed by only operating on one mesh at a time.
253 Editing is where the 3 data types vary most.
255 - Polygons are very limited for editing,
256 changing materials and options like smooth works but for anything else
257 they are too inflexible and are only intended for storage.
258 - Tessfaces should not be used for editing geometry because doing so will cause existing ngons to be tessellated.
259 - BMesh-Faces are by far the best way to manipulate geometry.
265 All 3 data types can be used for exporting,
266 the choice mostly depends on whether the target format supports ngons or not.
268 - Polygons are the most direct & efficient way to export providing they convert into the output format easily enough.
269 - Tessfaces work well for exporting to formats which dont support ngons,
270 in fact this is the only place where their use is encouraged.
271 - BMesh-Faces can work for exporting too but may not be necessary if polygons can be used
272 since using bmesh gives some overhead because its not the native storage format in object mode.
275 Upgrading Importers from 2.62
276 -----------------------------
278 Importers can be upgraded to work with only minor changes.
280 The main change to be made is used the tessellation versions of each attribute.
282 - mesh.faces --> :class:`bpy.types.Mesh.tessfaces`
283 - mesh.uv_textures --> :class:`bpy.types.Mesh.tessface_uv_textures`
284 - mesh.vertex_colors --> :class:`bpy.types.Mesh.tessface_vertex_colors`
286 Once the data is created call :class:`bpy.types.Mesh.update` to convert the tessfaces into polygons.
289 Upgrading Exporters from 2.62
290 -----------------------------
292 For exporters the most direct way to upgrade is to use tessfaces as with importing
293 however its important to know that tessfaces may **not** exist for a mesh,
294 the array will be empty as if there are no faces.
296 So before accessing tessface data call: :class:`bpy.types.Mesh.update` ``(calc_tessface=True)``.
299 EditBones, PoseBones, Bone... Bones
300 ===================================
302 Armature Bones in Blender have three distinct data structures that contain them.
303 If you are accessing the bones through one of them, you may not have access to the properties you really need.
307 In the following examples ``bpy.context.object`` is assumed to be an armature object.
313 ``bpy.context.object.data.edit_bones`` contains a editbones;
314 to access them you must set the armature mode to edit mode first (editbones do not exist in object or pose mode).
315 Use these to create new bones, set their head/tail or roll, change their parenting relationships to other bones, etc.
317 Example using :class:`bpy.types.EditBone` in armature editmode:
319 This is only possible in edit mode.
321 >>> bpy.context.object.data.edit_bones["Bone"].head = Vector((1.0, 2.0, 3.0))
323 This will be empty outside of editmode.
325 >>> mybones = bpy.context.selected_editable_bones
327 Returns an editbone only in edit mode.
329 >>> bpy.context.active_bone
335 ``bpy.context.object.data.bones`` contains bones.
336 These *live* in object mode, and have various properties you can change,
337 note that the head and tail properties are read-only.
339 Example using :class:`bpy.types.Bone` in object or pose mode:
341 Returns a bone (not an editbone) outside of edit mode
343 >>> bpy.context.active_bone
345 This works, as with blender the setting can be edited in any mode
347 >>> bpy.context.object.data.bones["Bone"].use_deform = True
349 Accessible but read-only
351 >>> tail = myobj.data.bones["Bone"].tail
357 ``bpy.context.object.pose.bones`` contains pose bones.
358 This is where animation data resides, i.e. animatable transformations
359 are applied to pose bones, as are constraints and ik-settings.
361 Examples using :class:`bpy.types.PoseBone` in object or pose mode:
363 .. code-block:: python
365 # Gets the name of the first constraint (if it exists)
366 bpy.context.object.pose.bones["Bone"].constraints[0].name
368 # Gets the last selected pose bone (pose mode only)
369 bpy.context.active_pose_bone
374 Notice the pose is accessed from the object rather than the object data,
375 this is why blender can have 2 or more objects sharing the same armature in different poses.
379 Strictly speaking PoseBone's are not bones, they are just the state of the armature,
380 stored in the :class:`bpy.types.Object` rather than the :class:`bpy.types.Armature`,
381 the real bones are however accessible from the pose bones - :class:`bpy.types.PoseBone.bone`
384 Armature Mode Switching
385 -----------------------
387 While writing scripts that deal with armatures you may find you have to switch between modes,
388 when doing so take care when switching out of edit-mode not to keep references
389 to the edit-bones or their head/tail vectors.
390 Further access to these will crash blender so its important the script
391 clearly separates sections of the code which operate in different modes.
393 This is mainly an issue with editmode since pose data can be manipulated without having to be in pose mode,
394 however for operator access you may still need to enter pose mode.
404 A common mistake is to assume newly created data is given the requested name.
406 This can cause bugs when you add some data (normally imported) then reference it later by name.
408 .. code-block:: python
410 bpy.data.meshes.new(name=meshid)
412 # normally some code, function calls...
413 bpy.data.meshes[meshid]
416 Or with name assignment...
418 .. code-block:: python
422 # normally some code, function calls...
423 obj = bpy.data.meshes[objname]
426 Data names may not match the assigned values if they exceed the maximum length, are already used or an empty string.
429 Its better practice not to reference objects by names at all,
430 once created you can store the data in a list, dictionary, on a class etc,
431 there is rarely a reason to have to keep searching for the same data by name.
433 If you do need to use name references, its best to use a dictionary to maintain
434 a mapping between the names of the imported assets and the newly created data,
435 this way you don't run this risk of referencing existing data from the blend file, or worse modifying it.
437 .. code-block:: python
439 # typically declared in the main body of the function.
440 mesh_name_mapping = {}
442 mesh = bpy.data.meshes.new(name=meshid)
443 mesh_name_mapping[meshid] = mesh
445 # normally some code, or function calls...
447 # use own dictionary rather then bpy.data
448 mesh = mesh_name_mapping[meshid]
454 Blender keeps data names unique - :class:`bpy.types.ID.name` so you can't name two objects,
455 meshes, scenes etc the same thing by accident.
457 However when linking in library data from another blend file naming collisions can occur,
458 so its best to avoid referencing data by name at all.
460 This can be tricky at times and not even blender handles this correctly in some case
461 (when selecting the modifier object for eg you can't select between multiple objects with the same name),
462 but its still good to try avoid problems in this area.
465 If you need to select between local and library data, there is a feature in ``bpy.data`` members to allow for this.
467 .. code-block:: python
469 # typical name lookup, could be local or library.
470 obj = bpy.data.objects["my_obj"]
472 # library object name look up using a pair
473 # where the second argument is the library path matching bpy.types.Library.filepath
474 obj = bpy.data.objects["my_obj", "//my_lib.blend"]
476 # local object name look up using a pair
477 # where the second argument excludes library data from being returned.
478 obj = bpy.data.objects["my_obj", None]
480 # both the examples above also works for 'get'
481 obj = bpy.data.objects.get(("my_obj", None))
487 Blenders relative file paths are not compatible with standard Python modules such as ``sys`` and ``os``.
489 Built in Python functions don't understand blenders ``//`` prefix which denotes the blend file path.
491 A common case where you would run into this problem is when exporting a material with associated image paths.
493 >>> bpy.path.abspath(image.filepath)
496 When using blender data from linked libraries there is an unfortunate complication
497 since the path will be relative to the library rather then the open blend file.
498 When the data block may be from an external blend file pass the library argument from the :class:`bpy.types.ID`.
500 >>> bpy.path.abspath(image.filepath, library=image.library)
503 These returns the absolute path which can be used with native Python modules.
509 Python supports many different encodings so there is nothing stopping you from
510 writing a script in ``latin1`` or ``iso-8859-15``.
512 See `pep-0263 <http://www.python.org/dev/peps/pep-0263/>`_
514 However this complicates matters for Blender's Python API because ``.blend`` files don't have an explicit encoding.
516 To avoid the problem for Python integration and script authors we have decided all strings in blend files
517 **must** be ``UTF-8``, ``ASCII`` compatible.
519 This means assigning strings with different encodings to an object names for instance will raise an error.
521 Paths are an exception to this rule since we cannot ignore the existence of non ``UTF-8`` paths on users file-system.
523 This means seemingly harmless expressions can raise errors, eg.
525 >>> print(bpy.data.filepath)
526 UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-21: ordinal not in range(128)
528 >>> bpy.context.object.name = bpy.data.filepath
529 Traceback (most recent call last):
530 File "<blender_console>", line 1, in <module>
531 TypeError: bpy_struct: item.attr= val: Object.name expected a string type, not str
534 Here are 2 ways around filesystem encoding issues:
536 >>> print(repr(bpy.data.filepath))
539 >>> filepath_bytes = os.fsencode(bpy.data.filepath)
540 >>> filepath_utf8 = filepath_bytes.decode('utf-8', "replace")
541 >>> bpy.context.object.name = filepath_utf8
544 Unicode encoding/decoding is a big topic with comprehensive Python documentation,
545 to avoid getting stuck too deep in encoding problems - here are some suggestions:
547 - Always use utf-8 encoding or convert to utf-8 where the input is unknown.
548 - Avoid manipulating filepaths as strings directly, use ``os.path`` functions instead.
549 - Use ``os.fsencode()`` / ``os.fsdecode()`` instead of built in string decoding functions when operating on paths.
550 - To print paths or to include them in the user interface use ``repr(path)`` first
551 or ``"%r" % path`` with string formatting.
555 Sometimes it's preferrable to avoid string encoding issues by using bytes instead of Python strings,
556 when reading some input its less trouble to read it as binary data
557 though you will still need to decide how to treat any strings you want to use with Blender,
558 some importers do this.
561 Strange errors using 'threading' module
562 =======================================
564 Python threading with Blender only works properly when the threads finish up before the script does.
565 By using ``threading.join()`` for example.
567 Heres an example of threading supported by Blender:
569 .. code-block:: python
575 print(threading.current_thread().name, "Starting")
577 # do something vaguely useful
579 from mathutils import Vector
580 from random import random
582 prod_vec = Vector((random() - 0.5, random() - 0.5, random() - 0.5))
583 print("Prodding", prod_vec)
584 bpy.data.objects["Cube"].location += prod_vec
585 time.sleep(random() + 1.0)
588 print(threading.current_thread().name, "Exiting")
590 threads = [threading.Thread(name="Prod %d" % i, target=prod) for i in range(10)]
593 print("Starting threads...")
598 print("Waiting for threads to finish...")
604 This an example of a timer which runs many times a second and moves
605 the default cube continuously while Blender runs **(Unsupported)**.
607 .. code-block:: python
612 bpy.data.objects['Cube'].location.x += 0.05
615 from threading import Timer
616 t = Timer(0.1, my_timer)
622 Use cases like the one above which leave the thread running once the script finishes
623 may seem to work for a while but end up causing random crashes or errors in Blender's own drawing code.
625 So far, no work has gone into making Blender's Python integration thread safe,
626 so until its properly supported, best not make use of this.
630 Pythons threads only allow co-currency and won't speed up your scripts on multi-processor systems,
631 the ``subprocess`` and ``multiprocess`` modules can be used with Blender and make use of multiple CPU's too.
634 Help! My script crashes Blender
635 ===============================
637 Ideally it would be impossible to crash Blender from Python
638 however there are some problems with the API where it can be made to crash.
640 Strictly speaking this is a bug in the API but fixing it would mean adding memory verification
641 on every access since most crashes are caused by the Python objects referencing Blenders memory directly,
642 whenever the memory is freed, further Python access to it can crash the script.
643 But fixing this would make the scripts run very slow,
644 or writing a very different kind of API which doesn't reference the memory directly.
646 Here are some general hints to avoid running into these problems.
648 - Be aware of memory limits,
649 especially when working with large lists since Blender can crash simply by running out of memory.
650 - Many hard to fix crashes end up being because of referencing freed data,
651 when removing data be sure not to hold any references to it.
652 - Modules or classes that remain active while Blender is used,
653 should not hold references to data the user may remove, instead,
654 fetch data from the context each time the script is activated.
655 - Crashes may not happen every time, they may happen more on some configurations/operating-systems.
659 To find the line of your script that crashes you can use the ``faulthandler`` module.
660 See `faulthandler docs <http://docs.python.org/dev/library/faulthandler.html>`_.
662 While the crash may be in Blenders C/C++ code,
663 this can help a lot to track down the area of the script that causes the crash.
669 Undo invalidates all :class:`bpy.types.ID` instances (Object, Scene, Mesh, Lamp... etc).
671 This example shows how you can tell undo changes the memory locations.
673 >>> hash(bpy.context.object)
675 >>> hash(bpy.context.object)
678 # ... move the active object, then undo
680 >>> hash(bpy.context.object)
683 As suggested above, simply not holding references to data when Blender is used
684 interactively by the user is the only way to ensure the script doesn't become unstable.
690 One of the advantages with Blenders library linking system that undo
691 can skip checking changes in library data since it is assumed to be static.
693 Tools in Blender are not allowed to modify library data.
695 Python however does not enforce this restriction.
697 This can be useful in some cases, using a script to adjust material values for example.
698 But its also possible to use a script to make library data point to newly created local data,
699 which is not supported since a call to undo will remove the local data
700 but leave the library referencing it and likely crash.
702 So it's best to consider modifying library data an advanced usage of the API
703 and only to use it when you know what you're doing.
706 Edit Mode / Memory Access
707 -------------------------
709 Switching edit-mode ``bpy.ops.object.mode_set(mode='EDIT')`` / ``bpy.ops.object.mode_set(mode='OBJECT')``
710 will re-allocate objects data,
711 any references to a meshes vertices/polygons/uvs, armatures bones,
712 curves points etc cannot be accessed after switching edit-mode.
714 Only the reference to the data its self can be re-accessed, the following example will crash.
716 .. code-block:: python
718 mesh = bpy.context.active_object.data
719 polygons = mesh.polygons
720 bpy.ops.object.mode_set(mode='EDIT')
721 bpy.ops.object.mode_set(mode='OBJECT')
727 So after switching edit-mode you need to re-access any object data variables,
728 the following example shows how to avoid the crash above.
730 .. code-block:: python
732 mesh = bpy.context.active_object.data
733 polygons = mesh.polygons
734 bpy.ops.object.mode_set(mode='EDIT')
735 bpy.ops.object.mode_set(mode='OBJECT')
737 # polygons have been re-allocated
738 polygons = mesh.polygons
742 These kinds of problems can happen for any functions which re-allocate
743 the object data but are most common when switching edit-mode.
749 When adding new points to a curve or vertices's/edges/polygons to a mesh,
750 internally the array which stores this data is re-allocated.
752 .. code-block:: python
754 bpy.ops.curve.primitive_bezier_curve_add()
755 point = bpy.context.object.data.splines[0].bezier_points[0]
756 bpy.context.object.data.splines[0].bezier_points.add()
759 point.co = 1.0, 2.0, 3.0
761 This can be avoided by re-assigning the point variables after adding the new one or by storing
762 indices's to the points rather then the points themselves.
764 The best way is to sidestep the problem altogether add all the points to the curve at once.
765 This means you don't have to worry about array re-allocation and its faster too
766 since reallocating the entire array for every point added is inefficient.
772 **Any** data that you remove shouldn't be modified or accessed afterwards,
773 this includes f-curves, drivers, render layers, timeline markers, modifiers, constraints
774 along with objects, scenes, groups, bones.. etc.
776 The ``remove()`` api calls will invalidate the data they free to prevent common mistakes.
778 The following example shows how this precortion works.
780 .. code-block:: python
782 mesh = bpy.data.meshes.new(name="MyMesh")
783 # normally the script would use the mesh here...
784 bpy.data.meshes.remove(mesh)
785 print(mesh.name) # <- give an exception rather then crashing:
787 # ReferenceError: StructRNA of type Mesh has been removed
790 But take care because this is limited to scripts accessing the variable which is removed,
791 the next example will still crash.
793 .. code-block:: python
795 mesh = bpy.data.meshes.new(name="MyMesh")
796 vertices = mesh.vertices
797 bpy.data.meshes.remove(mesh)
798 print(vertices) # <- this may crash
804 Some Python modules will call ``sys.exit()`` themselves when an error occurs,
805 while not common behavior this is something to watch out for because it may seem
806 as if Blender is crashing since ``sys.exit()`` will close Blender immediately.
808 For example, the ``argparse`` module will print an error and exit if the arguments are invalid.
810 An ugly way of troubleshooting this is to set ``sys.exit = None`` and see what line of Python code is quitting,
811 you could of course replace ``sys.exit`` with your own function but manipulating Python in this way is bad practice.