parent an object to a bone in python
I have been having a similar problem and using bone.length only works if the head of the bone is on the origin.
A more general solution is to find the vector from the tail back to the head and add that to the parent_matrix_inverted.
This function appears to work for bones regardless of their orientation. Note the rig must be in pose mode for this work otherwise rig.pose.bones will be empty.
def parentBone(rig, boneName, geo):
    bpy.context.evaluated_depsgraph_get().update()
    bone = rig.pose.bones[boneName]

    geo.parent=rig
    geo.parent_type = &quot;BONE&quot;
    geo.parent_bone = boneName

    vec = bone.head - bone.tail
    trans = mathutils.Matrix.Translation(vec)
    geo.matrix_parent_inverse = bone.matrix.inverted() @ trans