How to add local attributes of an operator to a `bpy.app.handle`? I want to add local attributes of an operator to a bpy.app.handle.

So my solution was this:

import bpy

class ModalOperator(bpy.types.Operator):
    """Add a handle"""
    bl_idname = "object.add_handle"
    bl_label = "Simple Add Handle Operator"

    def handle(self, scene):
        frame = scene.frame_current
        if frame in self.param:
            print(frame, '=', self.param[frame])
        else:
            print("frame %d added to cache" % frame)
            self.param[frame] = "cached"


    def invoke(self, context, event):
        self.param = {self: 'my dict'}

        print(bpy.app.handlers.frame_change_post)
        print(self.handle in bpy.app.handlers.frame_change_post) # Always False
        #bpy.app.handlers.frame_change_post.clear()

        bpy.app.handlers.frame_change_post.append(self.handle)

        return {'RUNNING_MODAL'}


def register():
    bpy.utils.register_class(ModalOperator)


def unregister():
    bpy.utils.unregister_class(ModalOperator)


if __name__ == "__main__":
    register()

    # test call
    bpy.ops.object.add_handle('INVOKE_DEFAULT')


To explain, I added a method of the operator to bpy.app.handlers.frame_change_post. And I had to return 'RUNNING_MODAL' because any other would destroy the operator

I do not know if this solution is good, because when it registers the same operator consecutively, the previous one is not destroyed (since it was referenced in the handle function);
And it is also not easy to know if the handle has already been added and should be replaced.

So... How to fix these problems? Or how to get a better solution to add a context to a specific handle??
This can be done by defining a function in the namespace where your variables are accessible:

    def invoke(self, context, event):
        self.param = {self: 'my dict'}

        print(bpy.app.handlers.frame_change_post)
        print(self.handle in bpy.app.handlers.frame_change_post) # Always False
        #bpy.app.handlers.frame_change_post.clear()

        # local function that can access this namespace
        def handle_local(scene):
            # pass any vars you want
            self.handle(self, scene, context)

        bpy.app.handlers.frame_change_post.append(handle_local)

        return {'RUNNING_MODAL'}


Note: the line print(self.handle in bpy.app.handlers.frame_change_post) is no longer correct, using a function defined each time makes this check more involved.