# Calling delete() operator after revert_mainfile()

I have a script that tries to derive several blend files from the same source file. However after a while I realised that the delete() operator apparently doesn't work after reverting the file. I could nail it down to this, that can be run with the default startup scene.

import bpy

# if this line is removed, delete() behaves as expected.
bpy.ops.wm.revert_mainfile()

bpy.context.scene.objects['Cube'].select=True
bpy.ops.object.delete()


Expected result: Cube should be deleted.

Actual result: Cube is selected, but not deleted

This can be tested by copying the script in a text window and hitting 'Run Script'

EDIT: It's been suggested that I should refresh the UI to see the result. This is irrelevant to the problem. (As I did) you can confirm that nothing was deleted programmatically.

It is basically a timing issue: your code below revert_mainfile() is called before the scene is ready, it's simply too early.

A load_post handler alone doesn't help either, the argument passed to this callback is None.

If you register a persistent load_post handler, which sets up a scene_update_pre handler, the execution will be delayed until the scene is ready:

import bpy
from bpy.app.handlers import persistent

def scene_update_callback(scene):

# self-removal, only run once
bpy.app.handlers.scene_update_pre.remove(scene_update_callback)

ob = scene.objects.get("Cube")

if ob is not None:
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
ob.select = True
bpy.ops.object.delete()

@persistent