How to use global variable used in multiple frames

I need to use a list in a script, and that list needs to be accessed by multiple frames during full animation renders. If you run the script and then render the animation foo behaves as expected with 100,101,102… but if you do it a second time the globally scoped foo in my_handler is not respecting the initializiation of foo = 100. And That global foo is pointing to the old value.

Anyone have an idea the best way to deal with this.

Simple example:


import bpy

def my_handler(scene):
    global foo
    print("Foo Change", foo)
    foo = foo + 1

foo = 100
print("Foo Start ------------------------------------", foo)
bpy.app.handlers.frame_change_pre.append(my_handler)

the register function installs a class for execution in the bpy.ops module and just like any other object in python you can set anything you want in there and it will stay. even in the game engine the classes/functions that are cached when running can store any variables as long as they are not rudimentary types(int,str,bytes,bytearray);

Running this piece of code twice:


import bpy


def myhandler(scene):
    pass


handlers = bpy.app.handlers.frame_change_pre
handlers.append(myhandler)

Will give you this:


>>> bpy.app.handlers.frame_change_pre
[<function myhandler at 0x00000040A0580EA0>, <function myhandler at 0x00000040A0615D90>]

This means that the handler will always be registered every time. So you will need to clear the handlers as a precaution.


import bpy


def myhandler(scene):
    pass


handlers = bpy.app.handlers.frame_change_pre
handlers.clear()
handlers.append(myhandler)

Now I test it and it looks like it works, foo starts from 100:


import bpy


foo = 100


def myhandler(scene):
    global foo
    print("Foo ", foo)
    foo += 1


handlers = bpy.app.handlers.frame_change_pre
handlers.clear()
handlers.append(myhandler)