magicgui
type registration#
magicgui
uses
type hints to infer the appropriate widget type
for a given function parameter. It allows third party packages
(like napari
) to register support for their types using
register_type()
. napari
registers
a number of types, additionally specifying, where appropriate:
widget type for the parameter type
function for updating inputs for the widget
return callback, for return types
This enables magicgui
widgets to be easily created via type annotations.
Note
This page provides implementation details on napari
-specific type registration
in magicgui
and is aimed at napari
developers.
For information about using magicgui
(for users and plugin developers) see
Creating widgets.
Registration details#
napari
types are either registered via the
@register_type
decorator when they are
defined or in
napari/types.py
.
For the full list of types registered, see Parameter annotations.
Layer types#
The ‘layer’ types registered are Layer
and its subclasses, and
<LayerType>Data
types.
All these types provide a choices
callable when they are registered with
magicgui
. This means that annotating with these types creates a
CategoricalWidget
, which will have a dropdown
selection whose options will be updated via the
choices
callable.
This callable is either get_layers_data
or get_layers
.
These functions retrieve the closest parent Viewer
of the native
CategoricalWidget
widget and returns a list of
Layer
or tuple of format ('layer name', <LayerType>Data)
.
This callable is set to the choices
attribute of the
CategoricalWidget
in its
reset_choices()
method and thus
gets called via CategoricalWidget
’s choices
setter.
napari
add_dock_widget()
checks if the dock widget has
a reset_choices
attribute and if so, connects it to layer events.
Note that magicgui
ContainerWidget
’s will call
reset_choices
on all subwidgets. This means that when the dock widget is a
ContainerWidget
, any subwidgets (e.g.,
CategoricalWidget
s) are updated
whenever layers change.
Note that add_dock_widget()
will
connect any existing reset_choices
widget attribute to layer events for all widgets,
not just magicgui
widgets.
The ‘layer’ types also specify a return_callback
function that adds the layer
to the closest parent Viewer
of the native widget when a ‘layer’ type is a return
annotation.
Viewer
type#
Viewer
differs from the layer types. napari
simply specifies
that the closest parent Viewer
(technically a public proxy of
the Viewer
that prevents private attribute access) be bound to
the widget (technically it’s bound to a hidden child
EmptyWidget
). This allows the Viewer
to be used in the magicgui
widget.
Note
When widget is not a magicgui
widget, the Viewer
is provided
via a wrapper napari
adds around widget contributions.
Generalization of magicgui
type annotation#
napari
generalizes magicgui
type annotation behaviour beyond widgets, to all
actions via app-model
providers and processors. See Dependency injection and result processing
for details.