How to properly define callbacks and delete them later in maya?

I want to define my own callbacks as follows, for some reason I can not use scriptJob, The following code snippet works ( I mean in global namespace it works, I can run it in script editor ), but how do I integrate it into a custom menu or into a shelf button?

Say if I decided to put the code into a module file. a.py Then how do I manage all the created callbacks and how do I delete them later when I don’t need them ? The only solution I can think of are:

[ol]
[li] make callbacks a module variable, and update it when new callbacks are created, access it by using a.callbacks, and delete them when they are not needed
[/li][li] create a hidden pyqt window, save the callback instances and functions inside the window, and delete them when window is closed
[/li][/ol]

which is a better solution ? or both of them are not recommended?

the code is from maya-python group


callbacks = []

def do_something():
    print "anything"

def main():
    global callbacks
    idx = OpenMaya.MEventMessage.addEventCallback("timeChanged", get_sec)
    callbacks.append(idx)

def remove_callbacks():
    for call in callbacks:
        OpenMaya.MMessage.removeCallback(call)

Module variables are fine, there’s no need for a class unless you need to group the callbacks or manage the whole set at once. The example code is fine, if this were we a module you’d just do


import mymodule
mymodule.main()

mymodule.remove_callbacks()

and so on. You probably want to be more granular than adding and removing them all at once – and you’ll probably need to be able to list them as well.

are you sure you want to manage callbacks globally? I mean - you can define some callbacks for the pipeline, some for the widgets etc. Now if you let’s say - remove all the callbacks on widget close then your pipeline callbacks won’t work anymore.
By pipeline callbacks I mean things like sanity checks on file open/close etc. while the widget might want to react on selection change, creating a reference or something.