"Context is Invalid"

I’m working on an import script and am hitting a problem that I’m sure is simple, but I haven’t found a solution and Google isn’t finding much either.

I’m trying to create an armature and then put it into edit mode so I can add bones to it:

    armature_data = bpy.data.armatures.new("Armature")
    armature = bpy.data.objects.new("Armature", armature_data)
    armature.show_x_ray = True
    armature.data.draw_type = 'OCTAHEDRAL'
    armature.select = True

    bpy.ops.object.mode_set(mode='EDIT', toggle=False)

The last line of code always gives me the error:

SystemError: Operator bpy.ops.object.mode_set.poll() failed, context is incorrect
location: <unknown location>:-1

If anyone sees what I’m doing wrong, I’d appreciate a nudge in the right direction.

Thanks much,
Jeff

You need to link the object to the current scene and make it the active object. For fun, I added some bones to the armature too.

import bpy

armature_data = bpy.data.armatures.new("Armature")
armature = bpy.data.objects.new("Armature", armature_data)
armature.show_x_ray = True
armature.data.draw_type = 'OCTAHEDRAL'

scn = bpy.context.scene
scn.objects.link(armature)
scn.objects.active = armature

bpy.ops.object.mode_set(mode='EDIT', toggle=False)

for n in range(4):
    eb = armature_data.edit_bones.new("B%d" % n)
    eb.head = (n,0,0)
    eb.tail = (n,0,1)

bpy.ops.object.mode_set(mode='POSE', toggle=False)