Registering callback functions for events in napari?

I am asking this here, because it is not really an issue but a usage question. Let me know if you prefer this on github issues.

If I want to register callback functions for certain events in napari, what is the correct way to do it?
For mouse callback functions you provide a decorator-style interface, e.g. @viewer.mouse_drag_callbacks.append that wraps the function.

Now I want to create a callback function that is called whenever say a layer is added to the viewer.
I could not find a decorator functionality for this, but digging around in the source code and exploring with the ipython console I found that I can do this:

def handler(arg):
    print("type", arg.type)
    print("source", arg.source)
    print("index", arg.index)
    print("native", arg.native)

viewer.layers.events.emitters['added'].connect(handler)

which seems to do what I want. Now I’m not sure whether this is the intended way to or whether there is also a decorator-style way to register callbacks?

1 Like

@VolkerH asking here is fine. Right now using the connect syntax is the only way to connect to events like that, but I did raise an issue on the repo to try and drive discussion around what a standardized approach to connecting events could be. I’ll give this some more thought and then respond further. Curious if others have thoughts on the approach we should take too

1 Like

Thanks @sofroniewn. In this case I will use connect, except for mouse callbacks where I’ll use the decorators.

1 Like

Hi @VolkerH, you can use it as a decorator like so:

@viewer.layers.events.added.connect
 def handler(arg):
    print("type", arg.type)
    print("source", arg.source)
    print("index", arg.index)
    print("native", arg.native)

Any function that has exactly one required positional argument can be used as a decorator. See this post for more information on decorators and the “@” syntactic sugar.

2 Likes