Parent object to a bone and object becomes offsets! How do I prevent object from moving? I have just spent the better part of my day trying many different examples in an attempt to simply parent an object to a bone without the object moving (aka keep_transform). But no matter what I try it always offsets:

object.parent = armature
object.parent_bone = bone #object now in weird position
object.parent_type = 'BONE'


I also tried this as suggested here:

object.parent = armature
object.parent_bone = bone
bpy.context.active_pose_bone
bpy.ops.object.parent_set(type='BONE', keep_transform=True)


But get error "Error: No active bone"

I notice the object I am parenting to the bone in the armature is always moving to the bone's tail when I need it to be positioned at the head. 

Is there anything I can do to programmatically affix the object to the bone's head? Any help her would be most encouraging, I just keep hitting walls with this.

One idea I had was to just offset the object by the head/tail delta, but because blender allows parenting-in-place I figured I should stick to convention.

Thanks.
I have just tested batFINGER's code in Blender 2.79b, there is a bug in the formula.

When you multiply armature's world matrix with pose bone's object space matrix, you actually reached the bone head, not the bone tip, so you need to walk a bone's length to the bone tip, which is the origin of the pose bone.

Pose bone has a 'head' property and a 'tail' property, so we can calculate the bone vector, which equals to bone.tail minus bone.head.

I have verified the code in my project, it works correctly.

Here is the bug fixed version:

import bpy
context = bpy.context
from mathutils import Matrix
scene = context.scene
armature = scene.objects.get("Armature")
cube = scene.objects.get("Cube")

if cube and armature:
    cube.parent = armature
    bone = armature.pose.bones.get("Bone")
    cube.parent_bone = bone.name
    cube.parent_type = 'BONE'
    # keep current location
    cube.matrix_parent_inverse = (armature.matrix_world * Matrix.Translation(bone.tail - bone.head) * bone.matrix).inverted()