Blender Stack Exchange is a question and answer site for people who use Blender to create 3D graphics, animations, or games. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 3 down vote accepted

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.

share|improve this answer

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):
    #your script here

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

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

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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.