Why this script doesn't run as expected? I want to have a function which deselects currently selected objects, selects a passed object, runs a callback function and then restores the selection.
For example in my scene I have two objects Red and Blue. I select the Red object, run this script:

context = bpy.context
data = bpy.data
red = data.objects['Red']
blue = data.objects['Blue']

def select_run_deselect(obj, callback):
    """Selects given obj, runs callback and restores selection"""
    selected_objects = context.selected_objects
    active_object = context.active_object
    #Deselect selected objects.
    for s in selected_objects:
        s.select_set(False)
    #Select given object.
    obj.select_set(True)
    context.view_layer.update()
    #Run callback.
    callback()
    #Restore selection
    obj.select_set(False)
    for obj in selected_objects:
        obj.select_set(True)
    active_object.select_set(True)

select_run_deselect(blue, lambda: print(context.active_object.name))


and expect the output to be "Blue", but it prints "Red" instead.
Set the active object with 

context.view_layer.objects.active = obj


The active object can be active and unselected.