# Insert keyframe through python and set its properties

i'm trying to set some keyframe values programatically after its creation, and for now, i didn't find a way to return this keyframe properly, i have to loop through the entire fcurve which is not very efficient...

For example, i would like something like that :

# add a location x keyframe on frame 1
new_key = object.keyframe_insert(
"location",
index = 0,
frame = 1,
)

# set keyframe left handle type
new_key.handle_left_type = "VECTOR"

# set keyframe value
new_key.co[1] = "10"


But the keyframe_insert() method only return a Bool for succeeding or not in keyframe creation.

Do you guys know a way to get the keyframe the proper way ? Really stuck here !

But the keyframe_insert() method only return a Bool for succeeding or not in keyframe creation.

Do you guys know a way to get the keyframe the proper way ? Really stuck here !

• See blender.stackexchange.com/questions/64447/… ob.keyframe_insert creates action, fcurve etc if need be, whereas you wish to get a reference to the fcurves keyframe_point. Also related blender.stackexchange.com/questions/55858/… Mar 4 at 12:03
• thanks for pointing me in the right direction ! the fcurves.keyframe_point.insert() method is definitly the one to go with here ! cheers ! Mar 4 at 13:17

Found a solution using this related thread https://blender.stackexchange.com/a/32540/31246 and this How do I add keyframes to a newly created action with no associated objects? (thanks @batFinger)

Here is the resulting code where i already have a bunch of variable (frame, value, data_path, array_index, handle_left_type) :

# parent is the object/node_tree ... containing the animation_data
# get_unique_name is(collection, base_name) is a function to ensure name is not used,
# and if so iterate by adding numbers

# find fcurve
if parent.animation_data is None:
parent.animation_data_create()
a_d = parent.animation_data

if a_d.action is None:
new_name = get_unique_name(bpy.data.actions, parent.name + "Action")
a_d.action = bpy.data.actions.new(new_name)

fc = a_d.action.fcurves.find(data_path, index = array_index)
if fc is None:
fc = a_d.action.fcurves.new(data_path, index = array_index, action_group = group_name)

new_key = fc.keyframe_points.insert(
frame,
value
)
new_key.handle_left_type = old_handle_left_type


Cheers !