Global variables and undo

Hello guys, I would like to ask you something that most definitely you came across. I have created a panel in which i have several operators. They all act at the same object so i define global variables inside the operators for convenience. The problem i am facing is the following.

Lets suppose that in operator “Op1” i have:

global x
x=bpy.context.scene.objects.get(“some object”)

Then i run “Op2” that uses the variable x and it runs with no error but i don’t like the result.
I click undo.
Finally, i try rerunning “Op2” but x is no longer a defined variable so i receive an error. Both operators have in bl_options UNDO.

A quick solution would be to define a function as:

reminder()

if “some object” in bpy.context.scene.objects:
x=bpy.context.scene.objects.get(“some object”)

and call the function from every operator but that does not work with numbers for example.

global r

r=bpy.context.scene.cursor_location[2]

How can i avoid that?

there’s no need for

if "some object" in bpy.context.scene.objects:
x=bpy.context.scene.objects.get("some object")

if you use .get(), then simply give it a default argument, e.g.:

x = bpy.context.scene.objects.get("some object")
if x is None:
    return
# ...

Do you use REGISTER as well for bl_options?

Generally, as you got couple independent operators, I wouldn’t use any global’ed vars, but rather obtain current object from context every time.

I use register in bl_options as well. Thanks a lot for the help once more. I used to do it as you said in the end but to be more pretty and compact i switched to globals. Now going back again. :yes:
Exception handling did not cross my mind.

alright.

btw.

if you use .get(), then simply give it a default argument, e.g.:

i forgot to remove that sentence, you don’t need to supply a default value, there’s a default value of None already and you can check for that. But you could change it to something else, “is None” check is more reliable though