# Armature not in edit mode

I have a script that creates an armature in the first run, and then finds it in the second run. When I try to add a bone to it in the second run, I get this error: Armature 'Armature' not in edit mode, cannot add an editbone.

if armature_name in bpy.data.objects.keys():
armature = bpy.data.objects[armature_name]
armature_data = armature.data
print ('armature found')
else:
armature = bpy.context.object
armature.name = armature_name
armature_data = armature.data
armature_created = True
print ('armature created')

#I was in object mode before
bpy.ops.object.editmode_toggle()
#Also tried bpy.ops.object.mode_set(mode='EDIT')

#This crashes the second time
bone = armature_data.edit_bones.new(bone_name)


What am I doing wrong? Why am I not in edit mode? It seems that I am in edit mode, but the armature thinks I'm not.

It's more reliable to tell Blender which mode to switch to instead of relying on editmode_toggle(), because there's an enter editmode option, so you can't be sure what mode an object is in after creation:

bpy.ops.object.mode_set(mode='EDIT')


BTW: this is better than your current code:

try:
armature = bpy.data.objects[armature_name]
except KeyError:
# create armature

• I've tried mode_set as well as toggle, and the problem is the same with either. I was using toggle as that was how it was done in a code snippet I was referencing. I will try your suggestion, thanks! Apr 8 '15 at 8:23
• I've given it a try, and this does not fix the problem :( Apr 8 '15 at 20:23

It turns out the problem was that the armature was not the active object. To make it the active object, I had to deselect the active object and then set the armature as the active object.

ob.select = False
bpy.context.scene.objects.active = armature
armature.select = True