# How to change to constant interpolation mode from a python script?

I have written a python script to create an animation out of a file containing the trajectory of some objects and I would like to switch to a constant mode of interpolation (I have one position per time step and other interpolation modes are really slow and not necessary in this case). The code is launched in the 3D view context.

I have put the following code:

area = bpy.context.area
old_type = area.type
area.type = 'GRAPH_EDITOR'
bpy.ops.graph.select_all_toggle()
bpy.ops.graph.interpolation_type(type='CONSTANT')
area.type = old_type


but it does nothing...

slightly simple option (probably not the best in the long run)

A toggle inverts, if all curves are selected it will select the curves that are not selected. The solution might be as simple as this.

bpy.ops.graph.select_all_toggle(invert=False)


Easy enough, but perhaps not very obvious.

kf = bpy.data.objects['Cube'].animation_data.action.fcurves[0].keyframe_points[0]
kf.interpolation = 'CONSTANT'


or for Keyframes on all F-Curves of that object

import bpy

obj = bpy.data.objects['Cube']
fcurves = obj.animation_data.action.fcurves
for fcurve in fcurves:
for kf in fcurve.keyframe_points:
kf.interpolation = 'CONSTANT'


Without seeing your code I can only assume things about it. You can use the Outliner (DataBlocks view) to get a reasonable idea of where to look in the API for these things.

If the script seems to behave slowly, it might not be the interpolation but the way the script adds keyframes. I Might be wrong but I assume you are using something like this to add keyframes:

bpy.ops.anim.keyframe_insert(type='Location', confirm_success=True)
# this does more than just add keyframes


This would be faster:

import bpy

positions = (0,0,2),(0,1,2),(3,2,1),(3,4,1),(1,2,1)
start_pos = (0,0,0)

ob = bpy.context.active_object

frame_num = 0

for position in positions:
bpy.context.scene.frame_set(frame_num)
ob.location = position
ob.keyframe_insert(data_path="location", index=-1)  # <-- this
frame_num += 10


Setting the interpolation type at creation time:

for position in positions:
bpy.context.scene.frame_set(frame_num)
ob.location = position
ob.keyframe_insert(data_path="location", index=-1)

for fcurve in ob.animation_data.action.fcurves:
kf = fcurve.keyframe_points[-1]
kf.interpolation = 'CONSTANT'
frame_num += 10