Iterate through bones of armature

Is it possible to iterate through the bones of an armature?

armature.data.bones[n]?

There is several ways to do this and it all depends on what you want and what mode you want to do it in, I have created a couple addons that deal with bones in various ways, and in doing so I have noticed a few oddities when it comes to iterating across them.

It can be fairly easy to access the bones incorrectly, as a result the bones themselves may not update as one would expect or you will be unable to adjust the bone options you seek because where you are targeting the bones they either do not have the option available or it is read only.

Bones are stored either with the object or the armature data. when it comes to edit bones, they are stored with the armature data, which can be accessed with either;

bpy.data.armatures[armature.name].edit_bones[bone.name]

or

bpy.context.active_object.data.edit_bones[bone.name]

Pose bones are stored with the object, and can be accessed this way;

bpy.context.active_object.pose.bones[bone.name]

If you wish to iterate across the selected edit bones use; (requires you to be in edit mode of an armature)

for bone in context.selected_editable_bones[:]:
  # do something

And if you wish to iterate across the selected pose bones; (requires you to be in pose mode of an armature)

for bone in context.selected_pose_bones[:]:
  # do something

And for iterating across all edit bones of the active object;

for bone in bpy.context.active_object.data.edit_bones[:]:
  # do something

Or iterating across all pose bones;

for bone in bpy.context.active_object.pose.bones[:]:
  # do something

This should be enough information to get anyone needing to iterate across bones up and going.

6 Likes