def animate_visibility(ob, switch=-1):
    '''
    add 2 keys to keyframe visibility:
    switch options:
    nohting or -1 = auto (set the inverse of actual state)
    0 = visible before
    1 = visible after
    '''

    T = bpy.context.scene.frame_current

    if switch == -1:
        ob.keyframe_insert(data_path='hide_viewport', frame=T-1)
        ob.keyframe_insert(data_path='hide_render', frame=T-1)

        ob.hide_viewport = not ob.hide_viewport
        ob.hide_render = not ob.hide_render
        ob.keyframe_insert(data_path='hide_viewport', frame=T)
        ob.keyframe_insert(data_path='hide_render', frame=T)
    else:
        ob.hide_viewport = switch
        ob.hide_render = switch
        ob.keyframe_insert(data_path='hide_viewport', frame=T-1)
        ob.keyframe_insert(data_path='hide_render', frame=T-1)
        ob.hide_viewport = not switch
        ob.hide_render = not switch
        ob.keyframe_insert(data_path='hide_viewport', frame=T)
        ob.keyframe_insert(data_path='hide_render', frame=T)


for ob in bpy.context.selected_objects:
    animate_visibility(ob)#options : 0 = visible before / 1 = visible after (else automatic)