# Python - Undo script if script fails

Sometime when writing a python script I will run into an error such as syntax or some Exceptions. The script will partially execute, but not everything. This is frustrating because I have to manually undo what the script executed before I can run the script again. Is there a way that I can have the script undo what it has done if it fails. I want the script to only make permanent changes if it ran without error.

You could enable Undo support for your operator. Below

bl_label = "Simple Object Operator"


bl_options = {'REGISTER', 'UNDO'}


But I wouldn't make the operator undo itself on errors, rather let the user do it if necessarily. However, your script shouldn't raise exceptions in the first place, but check in the operator's poll() classmethod, if all pre-conditions are met. Or let it return {'CANCELLED'} inside the execute() body before something is damaged.

Wrap your script in an operator. You will only need one undo step then. Just replace the main function of this (shortened) template from Text Editor -> Python -> Operator Simple

import bpy

def main(context):
pass

class SimpleOperator(bpy.types.Operator):
bl_idname = "object.simple_operator"
bl_label = "Simple Object Operator"

def execute(self, context):
main(context)
return {'FINISHED'}

bpy.utils.register_class(SimpleOperator)
try:
bpy.ops.object.simple_operator()
except Exception as e:
print("something went wrong")
#raise the exception again
raise e


(See CoDeman's post). Using blender's undo system with bpy.ops.ed.undo is rather unreliable.

You may:

• check if requirements are met before performing your actions
• save some data with python and restore it if an error occured
• write a backup to disk and load it if an error occurred