magicclass package

Subpackages

Submodules

magicclass.core module

class magicclass.core.Parameters[source]

Bases: object

as_dict() dict[str, Any][source]

Convert parameter fields into a dictionary.

>>> class params(Parameters):
>>>     i = 1
>>>     j = 2
>>> p = params()
>>> p.as_dict() # {"i": 1, "j": 2}
magicclass.core.build_help(ui: MagicTemplate, parent=None) HelpWidget[source]

Build a widget for user guide. Once it is built, widget will be cached.

Parameters

ui (MagicTemplate) -- Magic class UI object.

Returns

Help of the input UI.

Return type

HelpWidget

magicclass.core.get_function_gui(ui: MagicTemplate, name: str) FunctionGuiPlus[source]

Get the FunctionGui object hidden beneath push button or menu.

This function is a helper function for magicclass.

Parameters
  • ui (MagicTemplate) -- Any of a magic-class instance.

  • name (str) -- Name of method (or strictly speaking, the name of PushButton).

Returns

FunctionGui object.

Return type

FunctionGuiPlus

magicclass.core.magicclass(class_: type | None = None, *, layout: str = 'vertical', labels: bool = True, name: str = None, visible: bool | None = None, close_on_run: bool = None, popup_mode: PopUpModeStr | PopUpMode = None, error_mode: ErrorModeStr | ErrorMode = None, widget_type: WidgetTypeStr | WidgetType = WidgetType.none, icon: Any | None = None, stylesheet: str | StyleSheet = None, properties: dict[str, Any] = None)[source]

Decorator that can convert a Python class into a widget.

>>> @magicclass
>>> class C:
>>>     ...
>>> ui = C()
>>> ui.show()  # open GUI
Parameters
  • class (type, optional) -- Class to be decorated.

  • layout (str, "vertical" or "horizontal", default is "vertical") -- Layout of the main widget.

  • labels (bool, default is True) -- If true, magicgui labels are shown.

  • name (str, optional) -- Name of GUI.

  • visible (bool, optional) -- Initial visibility of GUI. Useful when magic class is nested.

  • close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.

  • popup (bool, default is True) -- Deprecated.

  • popup_mode (str or PopUpMode, default is PopUpMode.popup) -- Option of how to popup FunctionGui widget when a button is clicked.

  • error_mode (str or ErrorMode, default is ErrorMode.msgbox) -- Option of how to raise errors during function calls.

  • widget_type (WidgetType or str, optional) -- Widget type of container.

  • icon (Any, optional) -- Path to the icon image or any object that can be converted into an icon.

  • stylesheet (str or StyleSheet object, optional) -- Set stylesheet to the widget if given.

  • properties (dict, optional) -- Set properties to the widget if given. This argument is useful when you want to set width, height or margin without defining __post_init__.

Return type

Decorated class or decorator.

magicclass.core.magiccontext(class_: type = None, *, into: Callable | None = None, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon: Any | None = None)[source]

Decorator that converts a Python class into a context menu. :param class_: Class to be decorated. :type class_: type, optional :param close_on_run: If True, magicgui created by every method will be deleted after the method is completed without

exceptions, i.e. magicgui is more like a dialog.

Parameters

popup_mode (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.

Return type

Decorated class or decorator.

magicclass.core.magicmenu(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon: Any | None = None)[source]

Decorator that converts a Python class into a menu bar. :param class_: Class to be decorated. :type class_: type, optional :param close_on_run: If True, magicgui created by every method will be deleted after the method is completed without

exceptions, i.e. magicgui is more like a dialog.

Parameters

popup_mode (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.

Return type

Decorated class or decorator.

magicclass.core.magictoolbar(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon: Any | None = None)[source]

Decorator that converts a Python class into a menu bar.

magicclass.core.repeat(ui: magicclass._gui._base.MagicTemplate, index: int = - 1) None[source]

Repeat last operation on GUI using recorded macro.

Parameters
  • ui (MagicTemplate) -- Target magic-class widget.

  • index (int, default is -1) -- Which execution will be repeated. Any object that support list slicing can be used. By default the last operation will be repeated.

magicclass.core.update_widget_state(ui: MagicTemplate, macro: Macro | str | None = None) None[source]

Update widget values based on a macro.

This helper function works similar to the update_widget method of FunctionGui. In most cases, this function will be used for restoring a state from a macro recorded before. Value changed signal will not be emitted within this operation.

Parameters
  • ui (MagicTemplate) -- Magic class instance.

  • macro (Macro or str, optional) -- An executable macro or string that dictates how GUI will be updated.

magicclass.help module

class magicclass.help.HelpWidget(ui=None, parent=None)[source]

Bases: magicclass.widgets.utils.FreeWidget

class magicclass.help.UiBoundTreeItem(parent, ui=None)[source]

Bases: PyQt5.QtWidgets.QTreeWidgetItem

child(self, int) QTreeWidgetItem[source]
takeChild(self, int) QTreeWidgetItem[source]
property ui
magicclass.help.get_help_info(ui: MagicTemplate) tuple[np.ndarray, dict[str, str]][source]
magicclass.help.get_keymap(ui: MagicTemplate | type[MagicTemplate])[source]

magicclass.plot_api module

Provide a matplotlib-like interface to plot data in a Qt widget. Import this submodule

>>> import magicclass.plot_api as plt

and it's ready to use like matplotlib.

>>> plt.plot(...)
>>> plt.title(...)
>>> plt.show()
magicclass.plot_api.close()[source]

Close current figure widget

magicclass.plot_api.draw()[source]

Draw current figure widget.

magicclass.plot_api.gcw() magicclass.widgets.plot.Figure[source]

Get current widget.

magicclass.plot_api.show()[source]

Show current figure widget.

magicclass.signature module

class magicclass.signature.AdditionalOptions[source]

Bases: TypedDict

copyto: str
gui: bool
into: str
keybinding: str
moveto: str
on_called: list[Callable]
record: bool
class magicclass.signature.MagicMethodSignature(parameters=None, *, return_annotation, gui_options: Optional[dict[str, dict]] = None, caller_options: Optional[dict[str]] = None, additional_options: Optional[dict[str]] = None)[source]

Bases: magicgui.signature.MagicSignature

This class also retains parameter options for PushButton itself, aside from the FunctionGui options that will be needed when the button is pushed.

classmethod from_signature(sig: inspect.Signature, gui_options=None, caller_options=None, additional_options=None) magicclass.signature.MagicMethodSignature[source]

Convert regular inspect.Signature to MagicSignature.

classmethod get_gui_options(sig: inspect.Signature | MagicSignature) dict[source]
replace(*, parameters=<class 'magicclass.signature._void'>, return_annotation: typing.Any = <class 'magicclass.signature._void'>) magicclass.signature.MagicMethodSignature[source]

Create a customized copy of the Signature.

Pass parameters and/or return_annotation arguments to override them in the new copy.

magicclass.signature.get_additional_option(obj: Any, option: str, default: Optional[Any] = None)[source]

Safely get an additional option from any objects.

magicclass.signature.split_annotated_type(annotation: _AnnotatedAlias) tuple[Any, dict][source]

Split an Annotated type into its base type and options dict.

magicclass.signature.upgrade_signature(func, gui_options: Optional[dict] = None, caller_options: Optional[dict] = None, additional_options: Optional[magicclass.signature.AdditionalOptions] = None)[source]

Upgrade function signature to MagicMethodSignature. The input function may have a inspect.Signature or magicgui.signature.Magicsignature.

Parameters
  • func (callable) -- Input function.

  • gui_options (dict, optional) -- Options of FunctionGui.

  • caller_options (dict, optional) -- Options of PushButton.

  • additional_options (AdditionalOptions, optional) -- Additional options that will be used in magic class.

Returns

Same function with upgraded signature

Return type

callable

magicclass.testing module

class magicclass.testing.MockConfirmation[source]

Bases: object

Class used for confirmation test.

assert_not_called()[source]
assert_value(text=None, gui=None)[source]
property value
magicclass.testing.click_methods(ui)[source]

magicclass.types module

class magicclass.types.Bound(*args)[source]

Bases: object

Make Annotated type from a MagicField or a method, such as:

>>> from magicclass import magicclass, field
>>> @magicclass
>>> class MyClass:
>>>     i = field(int)
>>>     def func(self, v: Bound[i]):
>>>         ...

Bound[value] is identical to Annotated[Any, {"bind": value}].

magicclass.types.Choices

alias of magicclass.types.OneOf

class magicclass.types.OneOf(*args)[source]

Bases: object

Make Annotated type from a method, such as:

>>> from magicclass import magicclass
>>> @magicclass
>>> class MyClass:
>>>     def func(self, v: OneOf[(1, 2, 3)]):
>>>         ...

OneOf[value] is identical to Annotated[Any, {"choices": value}].

class magicclass.types.Optional(*args, **kwargs)[source]

Bases: object

Make Annotated type similar to typing.Optional.

Arguments annotated with Optional[int] will create a OptionalWidget with a SpinBox as an inner widget.

>>> from magicclass import magicclass, set_options
>>> from magicclass.types import Optional
>>> @magicclass
>>> class A:
>>>     @set_options(a={"options": {"min": -1}})
>>>     def f(self, a: Optional[int]):
>>>         print(a)
>>> ui = A()
>>> ui.show()
class magicclass.types.SomeOf(*args)[source]

Bases: object

Make Annotated type from a method, such as:

>>> from magicclass import magicclass
>>> @magicclass
>>> class MyClass:
>>>     def func(self, v: Choices[(1, 2, 3)]):
>>>         ...

Choices[value] is identical to Annotated[Any, {"choices": value}].

class magicclass.types.Union(*args, **kwargs)[source]

Bases: object

Make Annotated type similar to typing.Union.

Arguments annotated with Union[int, str] will create a UnionWidget with a SpinBox and a LineEdit as inner widgets.

>>> from magicclass import magicclass
>>> from magicclass.types import Union
>>> @magicclass
>>> class A:
>>>     def f(self, a: Union[int, str]):
>>>         print(a)
>>> ui = A()
>>> ui.show()
class magicclass.types.WidgetType(value)[source]

Bases: enum.Enum

An enumeration.

button = 'button'
collapsible = 'collapsible'
draggable = 'draggable'
frame = 'frame'
groupbox = 'groupbox'
hcollapsible = 'hcollapsible'
list = 'list'
mainwindow = 'mainwindow'
none = 'none'
scrollable = 'scrollable'
split = 'split'
stacked = 'stacked'
subwindows = 'subwindows'
tabbed = 'tabbed'
toolbox = 'toolbox'
magicclass.types.bound(obj: Callable[[magicclass.types._W], magicclass.types._V]) type[_V][source]
magicclass.types.bound(obj: Callable[[Any, magicclass.types._W], magicclass.types._V]) type[_V]
magicclass.types.bound(obj: magicclass.fields._fields.MagicField[magicclass.types._W, magicclass.types._V]) type[_V]
magicclass.types.bound(obj: type[_W]) type

Function version of Bound[...].

magicclass.wrappers module

exception magicclass.wrappers.AbstractAPIError[source]

Bases: Exception

Raised when an abstract API is called.

exception magicclass.wrappers.Canceled[source]

Bases: RuntimeError

Raised when a function is canceled

class magicclass.wrappers.abstractapi(func: Callable | None = None)[source]

Bases: Callable

Wrapper used for marking abstract APIs.

This wrapper is intended to be used in combination with the wraps method of magic-classes.

Examples

>>> @magicclass
>>> class A:
...     @magicclass
...     class B:
...         @abstractapi  # mark as abstract
...         def f(self): ...
...         f = abstractapi()  # or like this
...     @B.wraps
...     def f(self, i: int):
...         print(i)  # do something
check_resolved() None[source]

Check if the abstract API has been resolved by wraps.

resolve() None[source]

Mark the API as solved.

magicclass.wrappers.bind_key(*key) Callable[[magicclass.wrappers.F], magicclass.wrappers.F][source]

Define a keybinding to a button or an action. This function accepts several styles of shortcut expression.

>>> @bind_key("Ctrl-A")         # napari style
>>> @bind_key("Ctrl", "A")      # separately
>>> @bind_key(Key.Ctrl + Key.A) # use Key class
>>> @bind_key(Key.Ctrl, Key.A)  # use Key class separately
magicclass.wrappers.confirm(*, text: str | None, condition: Callable[..., bool] | str | None, callback: Callable[[str, BaseGui], None] | None = 'None') Callable[[magicclass.wrappers.F], magicclass.wrappers.F][source]
magicclass.wrappers.confirm(f: magicclass.wrappers.F, *, text: str | None, condition: Callable[..., bool] | str | None, callback: Callable[[str, BaseGui], None] | None = 'None') magicclass.wrappers.F

Confirm if it is OK to run function in GUI.

Useful when the function will irreversibly delete or update something in GUI. Confirmation will be executed only when function is called in GUI.

Parameters
  • text (str, optional) -- Confirmation message, such as "Are you sure to run this function?". Format string can also be used here, in which case arguments will be passed. For instance, to execute confirmation on function f(a, b), you can use format string "Running with a = {a} and b = {b}" then confirmation message will be "Running with a = 1, b = 2" if f(1, 2) is called. By default, message will be "Do you want to run {name}?" where "name" is the function name.

  • condition (callable or str, optional) -- Condition of when confirmation will show up. If callable, it must accept condition(self) and return boolean object. If string, it must be evaluable as literal with input arguments as local namespace. For instance, function f(a, b) decorated by confirm(condition="a < b + 1") will evaluate a < b + 1 to check if confirmation is needed. Always true by default.

  • callback (callable, optional) -- Callback function when confirmation is needed. Must take a str and a BaseGui object as inputs. By default, message box will be shown. Useful for testing.

magicclass.wrappers.do_not_record(method: magicclass.wrappers.F) magicclass.wrappers.F[source]

Wrapped method will not be recorded in macro.

magicclass.wrappers.impl_preview(function: Callable | None = None, text: str = 'Preview', auto_call: bool = False)[source]

Define a preview of a function.

This decorator is useful for advanced magicgui creation. A "Preview" button appears in the bottom of the widget built from the input function and the decorated function will be called with the same arguments. Following example shows how to define a previewer that prints the content of the selected file.

>>> def func(self, path: Path):
...     ...
>>> @impl_preview(func)
>>> def _func_prev(self, path: Path):
...     with open(path, mode="r") as f:
...         print(f.read())
Parameters
  • function (callable, optional) -- To which function previewer will be defined. If not provided, the to-be- decorated function itself will be used as the preview function.

  • text (str, optional) -- Text of the preview button or checkbox.

  • auto_call (bool, default is False) -- Whether the preview function will be auto-called. If true, a check box will appear above the call button, and the preview function is auto-called during it is checked.

magicclass.wrappers.mark_on_called(function: Callable) Callable[[magicclass.wrappers._Fn], magicclass.wrappers._Fn][source]
magicclass.wrappers.mark_on_calling(function: Callable) Callable[[magicclass.wrappers._Fn], magicclass.wrappers._Fn][source]
magicclass.wrappers.mark_preview(function: Callable | None = None, text: str = 'Preview', auto_call: bool = False)

Define a preview of a function.

This decorator is useful for advanced magicgui creation. A "Preview" button appears in the bottom of the widget built from the input function and the decorated function will be called with the same arguments. Following example shows how to define a previewer that prints the content of the selected file.

>>> def func(self, path: Path):
...     ...
>>> @impl_preview(func)
>>> def _func_prev(self, path: Path):
...     with open(path, mode="r") as f:
...         print(f.read())
Parameters
  • function (callable, optional) -- To which function previewer will be defined. If not provided, the to-be- decorated function itself will be used as the preview function.

  • text (str, optional) -- Text of the preview button or checkbox.

  • auto_call (bool, default is False) -- Whether the preview function will be auto-called. If true, a check box will appear above the call button, and the preview function is auto-called during it is checked.

magicclass.wrappers.nogui(method: magicclass.wrappers.F) magicclass.wrappers.F[source]

Wrapped method will not be converted into a widget.

magicclass.wrappers.set_design(width: int | None = None, height: int | None = None, min_width: int | None = None, min_height: int | None = None, max_width: int | None = None, max_height: int | None = None, text: str | None = None, icon: str | None = None, font_size: int | None = None, font_family: int | None = None, font_color: Color | None = None, background_color: Color | None = None, visible: bool | None = None) Callable[[type[T]], type[T]] | Callable[[F], F][source]

Change button/action design by calling setter when the widget is created.

Parameters
  • width (int, optional) -- Button width. Call button.width = width.

  • height (int, optional) -- Button height. Call button.height = height.

  • min_width (int, optional) -- Button minimum width. Call button.min_width = min_width.

  • min_height (int, optional) -- Button minimum height. Call button.min_height = min_height.

  • max_width (int, optional) -- Button maximum width. Call button.max_width = max_width.

  • max_height (int, optional) -- Button maximum height. Call button.max_height = max_height.

  • text (str, optional) -- Button text. Call button.text = text.

  • icon (str, optional) -- Path to icon file. min_width and min_height will be automatically set to the icon size if not given.

  • font_size (int, optional) -- Font size of the text.

  • visible (bool default is True) -- Button visibility.

magicclass.wrappers.set_options(layout: str = 'vertical', labels: bool = True, call_button: bool | str | None = None, auto_call: bool = False, **options) Callable[[F], F][source]

Set MagicSignature to functions.

By decorating a method with this function, magicgui will create a widget with these options. These codes are similar in appearance.

# A magicgui way
@magicgui(a={...})
def func(a):
    ...

# A magicclass way
@magicclass
class A:
    @set_options(a={...})
    def func(self, a):
        ...
Parameters
  • layout (str, default is "vertical") -- The type of layout to use in FunctionGui. Must be one of {'horizontal', 'vertical'}.

  • labels (bool, default is True) -- Whether labels are shown in the FunctionGui.

  • call_button (bool or str, optional) -- If True, create an additional button that calls the original function when clicked. If a str, set the button text. If None (the default), it defaults to True when auto_call is False, and False otherwise.

  • auto_call (bool, optional) -- If True, changing any parameter in either the GUI or the widget attributes will call the original function with the current settings. by default False

  • options (dict) -- Parameter options.

Module contents

class magicclass.FieldGroup(layout: str = 'vertical', labels: bool = True, name: str | None = None, **kwargs)[source]

Bases: magicgui.widgets.Container, magicclass.fields._group.HasFields, magicclass.fields._fields._FieldObject

property callbacks: tuple[Callable, ...]

Return callbacks in an immutable way.

connect(callback: Callable)[source]
copy() Self[source]

Copy widget.

get_widget(obj) magicgui.widgets.Container[source]
class magicclass.HasFields[source]

Bases: object

A trait implemented with widgets and signals.

Subclasses can easily handle widgets and their value-change signals using the same attribute names.

>>> class A(HasFields):
>>>     a = vfield(int)
>>>     b = vfield(str)
>>> ins = A()
>>> ins.a  # type: int
>>> ins.widgets.a  # type: SpinBox
>>> ins.signals.a  # type: SignalInstance
property signals: magicclass.fields._group.SignalView

Return a view of signals.

property widgets: magicclass.fields._group.WidgetView

Return a view of widgets.

class magicclass.Icon[source]

Bases: types.SimpleNamespace

Namespace of icons.

from magicclass import magicclass, set_design, Icon

@magicclass
class A:
    @set_design(icon=Icon.FileIcon)
    def func(self):
        ...
ArrowBack = 54
ArrowDown = 51
ArrowForward = 55
ArrowLeft = 52
ArrowRight = 53
ArrowUp = 50
BrowserReload = 59
BrowserStop = 60
ComputerIcon = 15
CustomBase = -268435456
DesktopIcon = 13
DialogAbortButton = 74
DialogApplyButton = 45
DialogCancelButton = 40
DialogCloseButton = 44
DialogDiscardButton = 47
DialogHelpButton = 41
DialogIgnoreButton = 76
DialogNoButton = 49
DialogNoToAllButton = 72
DialogOkButton = 39
DialogOpenButton = 42
DialogResetButton = 46
DialogRetryButton = 75
DialogSaveAllButton = 73
DialogSaveButton = 43
DialogYesButton = 48
DialogYesToAllButton = 71
DirClosedIcon = 22
DirHomeIcon = 56
DirIcon = 38
DirLinkIcon = 23
DirLinkOpenIcon = 24
DirOpenIcon = 21
DockWidgetCloseButton = 8
DriveCDIcon = 18
DriveDVDIcon = 19
DriveFDIcon = 16
DriveHDIcon = 17
DriveNetIcon = 20
FileDialogBack = 37
FileDialogContentsView = 35
FileDialogDetailedView = 33
FileDialogEnd = 30
FileDialogInfoView = 34
FileDialogListView = 36
FileDialogNewFolder = 32
FileDialogStart = 29
FileDialogToParent = 31
FileIcon = 25
FileLinkIcon = 26
LineEditClearButton = 70
MediaPause = 63
MediaPlay = 61
MediaSeekBackward = 67
MediaSeekForward = 66
MediaSkipBackward = 65
MediaSkipForward = 64
MediaStop = 62
MediaVolume = 68
MediaVolumeMuted = 69
MessageBoxCritical = 11
MessageBoxInformation = 9
MessageBoxQuestion = 12
MessageBoxWarning = 10
RestoreDefaultsButton = 77
TitleBarCloseButton = 3
TitleBarContextHelpButton = 7
TitleBarMaxButton = 2
TitleBarMenuButton = 0
TitleBarMinButton = 1
TitleBarNormalButton = 4
TitleBarShadeButton = 5
TitleBarUnshadeButton = 6
ToolBarHorizontalExtensionButton = 27
ToolBarVerticalExtensionButton = 28
TrashIcon = 14
VistaShield = 58
class magicclass.Key(value)[source]

Bases: enum.Enum

An enumeration.

A = 'a'
Alt = 'alt'
Ampersand = '&'
Apostrophe = "'"
Asterisk = '*'
At = '@'
B = 'b'
Backspace = 'backspace'
C = 'c'
Colon = ':'
Comma = ','
Ctrl = 'ctrl'
D = 'd'
Delete = 'delete'
Dollar = '$'
Down = 'down'
E = 'e'
Equal = '='
Exclam = '!'
F = 'f'
F1 = 'f1'
F10 = 'f10'
F11 = 'f11'
F12 = 'f12'
F2 = 'f2'
F3 = 'f3'
F4 = 'f4'
F5 = 'f5'
F6 = 'f6'
F7 = 'f7'
F8 = 'f8'
F9 = 'f9'
G = 'g'
Greater = '>'
H = 'h'
I = 'i'
J = 'j'
K = 'k'
L = 'l'
Left = 'left'
Less = '<'
M = 'm'
Meta = 'meta'
Minus = '-'
N = 'n'
O = 'o'
P = 'p'
PageDown = 'pagedown'
PageUp = 'pageup'
ParenLeft = '('
ParenRight = ')'
Percent = '%'
Period = '.'
Plus = '+'
Q = 'q'
Question = '?'
R = 'r'
Right = 'right'
S = 's'
Semicolon = ';'
Shift = 'shift'
Slash = '/'
T = 't'
Tab = 'tab'
U = 'u'
Up = 'up'
V = 'v'
W = 'w'
X = 'x'
Y = 'y'
Z = 'z'
classmethod to_qtkey(key: str | int | Key) QtKey[source]
classmethod to_qtmodifier(key: str | Key) QtModifier[source]
class magicclass.MagicTemplate[source]

Bases: MutableSequence[magicclass._gui._base._W]

annotation: Any
changed: Signal
close() None[source]
enabled: bool
classmethod field(type_of_widget: type[_W], *, name: str | None = 'None', label: str | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') magicclass.fields._fields.MagicField[magicclass._gui._base._W, Any][source]
classmethod field(obj: type[_X], *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') MagicField[ValueWidget, _X]
classmethod field(obj: _X, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') MagicField[ValueWidget, _X]
classmethod field(gui_class: type[_M], *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') MagicField[_M, Any]
classmethod field(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: type[_W] = 'None', options: dict[str, Any] = '{}', record: bool = 'True') magicclass.fields._fields.MagicField[magicclass._gui._base._W, Any]
classmethod field(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') magicclass.fields._fields.MagicField[magicgui.widgets.bases._widget.Widget, Any]
classmethod field(*, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') magicclass.fields._fields.MagicField[magicgui.widgets.bases._widget.Widget, Any]

Make a MagicField object, with the widget in the child class.

>>> @magicclass
... class A:
...     @magicclass
...     class B:
...         i = ...  # pre-definition
...     i = B.field(1)
Parameters
  • obj (Any, default is Undefined) -- Reference to determine what type of widget will be created. If Widget subclass is given, it will be used as is. If other type of class is given, it will used as type annotation. If an object (not type) is given, it will be assumed to be the default value.

  • name (str, optional) -- Name of the widget.

  • label (str, optional) -- Label of the widget.

  • widget_type (str, optional) -- Widget type. This argument will be sent to create_widget function.

  • options (dict, optional) -- Widget options. This parameter will be passed to the options keyword argument of create_widget.

  • record (bool, default is True) -- A magic-class specific parameter. If true, record value changes as macro.

Return type

MagicField

find_ancestor(ancestor: type[_T], cache: bool = False) magicclass._gui._base._T[source]

Find magic class ancestor whose type matches the input.

This method is useful when a child widget class is defined outside a magic class while it needs access to its parent.

Parameters
  • ancestor (type of MagicTemplate) -- Type of ancestor to search for.

  • cache (bool, default is False) -- If true, the result will be cached. Caching is not safe if the widget is going to be used as a child of other widgets.

Returns

Magic class object if found.

Return type

MagicTemplate

gui_only: bool
height: int
hide() None[source]
icon: Any
insert(key: int, widget: _W | Callable) None[source]

S.insert(index, value) -- insert value before index

label: str
label_changed: Signal
labels: bool
layout: str
property macro: magicclass._gui._macro.GuiMacro

The macro object bound to the ancestor widget.

margins: tuple[int, int, int, int]
max_height: int
max_width: int
min_height: int
min_width: int
name: str
native: QWidget
objectName() str[source]

Return object name of the QWidget.

This function makes the object name discoverable by napari's viewer.window.add_dock_widget function. At the same time, since this function will always be called when the widget is added as a dock widget of napari, we can import macro recorders for napari types in the appropriate timing.

options: dict
param_kind: inspect._ParameterKind
parent: Widget
parent_changed: Signal
property parent_dock_widget: QDockWidget | None

Return dock widget object if magic class is a dock widget of a main window widget, such as a napari Viewer.

property parent_viewer: napari.Viewer | None

Return napari.Viewer if magic class is a dock widget of a viewer.

render() np.ndarray[source]
reset_choices(*args)[source]
show(run: bool) None[source]
tooltip: str
classmethod vfield(widget_type: type[_W], *, name: str | None = 'None', label: str | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') magicclass.fields._fields.MagicValueField[magicclass._gui._base._W, Any][source]
classmethod vfield(obj: _X, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') MagicValueField[ValueWidget, _X]
classmethod vfield(annotation: type[_X], *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') MagicValueField[ValueWidget, _X]
classmethod vfield(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: type[_W] = 'None', options: dict[str, Any] = '{}', record: bool = 'True') magicclass.fields._fields.MagicValueField[magicclass._gui._base._W, Any]
classmethod vfield(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, Any] = '{}', record: bool = 'True') magicclass.fields._fields.MagicValueField[magicgui.widgets.bases._widget.Widget, Any]
visible: bool
widget_type: str
width: int
classmethod wraps(method: _F | None = None, *, template: Callable | None = None, copy: bool = False) _F[source]

Wrap a parent method in a child magic-class.

Wrapped method will appear in the child widget but behaves as if it is in the parent widget. Basically, this function is used as a wrapper like below.

@magicclass
class C:
    @magicclass
    class D:
        def func(self, ...): ... # pre-definition
    @D.wraps
    def func(self, ...): ...
Parameters
  • method (Callable, optional) -- Method of parent class.

  • template (Callable, optional) -- Function template for signature.

  • copy (bool, default is False) -- If true, wrapped method is still enabled.

Returns

Same method as input, but has updated signature.

Return type

Callable

class magicclass.Parameters[source]

Bases: object

as_dict() dict[str, Any][source]

Convert parameter fields into a dictionary.

>>> class params(Parameters):
>>>     i = 1
>>>     j = 2
>>> p = params()
>>> p.as_dict() # {"i": 1, "j": 2}
class magicclass.PopUpMode(value)[source]

Bases: enum.Enum

Define how to popup FunctionGui.

above = 'above'
below = 'below'
dialog = 'dialog'
dock = 'dock'
first = 'first'
last = 'last'
parentlast = 'parentlast'
parentsub = 'parentsub'
popup = 'popup'
class magicclass.abstractapi(func: Callable | None = None)[source]

Bases: Callable

Wrapper used for marking abstract APIs.

This wrapper is intended to be used in combination with the wraps method of magic-classes.

Examples

>>> @magicclass
>>> class A:
...     @magicclass
...     class B:
...         @abstractapi  # mark as abstract
...         def f(self): ...
...         f = abstractapi()  # or like this
...     @B.wraps
...     def f(self, i: int):
...         print(i)  # do something
check_resolved() None[source]

Check if the abstract API has been resolved by wraps.

resolve() None[source]

Mark the API as solved.

magicclass.bind_key(*key) Callable[[magicclass.wrappers.F], magicclass.wrappers.F][source]

Define a keybinding to a button or an action. This function accepts several styles of shortcut expression.

>>> @bind_key("Ctrl-A")         # napari style
>>> @bind_key("Ctrl", "A")      # separately
>>> @bind_key(Key.Ctrl + Key.A) # use Key class
>>> @bind_key(Key.Ctrl, Key.A)  # use Key class separately
magicclass.build_help(ui: MagicTemplate, parent=None) HelpWidget[source]

Build a widget for user guide. Once it is built, widget will be cached.

Parameters

ui (MagicTemplate) -- Magic class UI object.

Returns

Help of the input UI.

Return type

HelpWidget

magicclass.confirm(f: F | None = None, *, text: str | None = None, condition: Callable[[BaseGui], bool] | str = None, callback: Callable[[str, BaseGui], None] | None = None)[source]

Confirm if it is OK to run function in GUI.

Useful when the function will irreversibly delete or update something in GUI. Confirmation will be executed only when function is called in GUI.

Parameters
  • text (str, optional) -- Confirmation message, such as "Are you sure to run this function?". Format string can also be used here, in which case arguments will be passed. For instance, to execute confirmation on function f(a, b), you can use format string "Running with a = {a} and b = {b}" then confirmation message will be "Running with a = 1, b = 2" if f(1, 2) is called. By default, message will be "Do you want to run {name}?" where "name" is the function name.

  • condition (callable or str, optional) -- Condition of when confirmation will show up. If callable, it must accept condition(self) and return boolean object. If string, it must be evaluable as literal with input arguments as local namespace. For instance, function f(a, b) decorated by confirm(condition="a < b + 1") will evaluate a < b + 1 to check if confirmation is needed. Always true by default.

  • callback (callable, optional) -- Callback function when confirmation is needed. Must take a str and a BaseGui object as inputs. By default, message box will be shown. Useful for testing.

magicclass.dataclass_gui(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)[source]

A dataclass-like decorator for GUI-implemented class.

@dataclass_gui
class A:
    i: int = vfield(int)
    s: str = vfield(str)

is identical to:

@dataclass
class A(HasFields):
    i: int = vfield(int)
    s: str = vfield(str)
Returns

GUI implemented class

Return type

HasField subtype

magicclass.do_not_record(method: magicclass.wrappers.F) magicclass.wrappers.F[source]

Wrapped method will not be recorded in macro.

magicclass.field(obj=<Undefined>, *, name=None, label=None, widget_type=None, options={}, record=True)[source]

Make a MagicField object.

>>> i = field(1)
>>> i = field(widget_type="Slider")
Parameters
  • obj (Any, default is Undefined) -- Reference to determine what type of widget will be created. If Widget subclass is given, it will be used as is. If other type of class is given, it will used as type annotation. If an object (not type) is given, it will be assumed to be the default value.

  • name (str, optional) -- Name of the widget.

  • label (str, optional) -- Label of the widget.

  • widget_type (str, optional) -- Widget type. This argument will be sent to create_widget function.

  • options (dict, optional) -- Widget options. This parameter will be passed to the options keyword argument of create_widget.

  • record (bool, default is True) -- A magic-class specific parameter. If true, record value changes as macro.

Return type

MagicField

magicclass.get_function_gui(ui: MagicTemplate, name: str) FunctionGuiPlus[source]

Get the FunctionGui object hidden beneath push button or menu.

This function is a helper function for magicclass.

Parameters
  • ui (MagicTemplate) -- Any of a magic-class instance.

  • name (str) -- Name of method (or strictly speaking, the name of PushButton).

Returns

FunctionGui object.

Return type

FunctionGuiPlus

magicclass.impl_preview(function: Callable | None = None, text: str = 'Preview', auto_call: bool = False)[source]

Define a preview of a function.

This decorator is useful for advanced magicgui creation. A "Preview" button appears in the bottom of the widget built from the input function and the decorated function will be called with the same arguments. Following example shows how to define a previewer that prints the content of the selected file.

>>> def func(self, path: Path):
...     ...
>>> @impl_preview(func)
>>> def _func_prev(self, path: Path):
...     with open(path, mode="r") as f:
...         print(f.read())
Parameters
  • function (callable, optional) -- To which function previewer will be defined. If not provided, the to-be- decorated function itself will be used as the preview function.

  • text (str, optional) -- Text of the preview button or checkbox.

  • auto_call (bool, default is False) -- Whether the preview function will be auto-called. If true, a check box will appear above the call button, and the preview function is auto-called during it is checked.

magicclass.magicclass(class_: type | None = None, *, layout: str = 'vertical', labels: bool = True, name: str = None, visible: bool | None = None, close_on_run: bool = None, popup_mode: PopUpModeStr | PopUpMode = None, error_mode: ErrorModeStr | ErrorMode = None, widget_type: WidgetTypeStr | WidgetType = WidgetType.none, icon: Any | None = None, stylesheet: str | StyleSheet = None, properties: dict[str, Any] = None)[source]

Decorator that can convert a Python class into a widget.

>>> @magicclass
>>> class C:
>>>     ...
>>> ui = C()
>>> ui.show()  # open GUI
Parameters
  • class (type, optional) -- Class to be decorated.

  • layout (str, "vertical" or "horizontal", default is "vertical") -- Layout of the main widget.

  • labels (bool, default is True) -- If true, magicgui labels are shown.

  • name (str, optional) -- Name of GUI.

  • visible (bool, optional) -- Initial visibility of GUI. Useful when magic class is nested.

  • close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.

  • popup (bool, default is True) -- Deprecated.

  • popup_mode (str or PopUpMode, default is PopUpMode.popup) -- Option of how to popup FunctionGui widget when a button is clicked.

  • error_mode (str or ErrorMode, default is ErrorMode.msgbox) -- Option of how to raise errors during function calls.

  • widget_type (WidgetType or str, optional) -- Widget type of container.

  • icon (Any, optional) -- Path to the icon image or any object that can be converted into an icon.

  • stylesheet (str or StyleSheet object, optional) -- Set stylesheet to the widget if given.

  • properties (dict, optional) -- Set properties to the widget if given. This argument is useful when you want to set width, height or margin without defining __post_init__.

Return type

Decorated class or decorator.

magicclass.magiccontext(class_: type = None, *, into: Callable | None = None, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon: Any | None = None)[source]

Decorator that converts a Python class into a context menu. :param class_: Class to be decorated. :type class_: type, optional :param close_on_run: If True, magicgui created by every method will be deleted after the method is completed without

exceptions, i.e. magicgui is more like a dialog.

Parameters

popup_mode (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.

Return type

Decorated class or decorator.

magicclass.magicmenu(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon: Any | None = None)[source]

Decorator that converts a Python class into a menu bar. :param class_: Class to be decorated. :type class_: type, optional :param close_on_run: If True, magicgui created by every method will be deleted after the method is completed without

exceptions, i.e. magicgui is more like a dialog.

Parameters

popup_mode (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.

Return type

Decorated class or decorator.

class magicclass.magicproperty(fget: Callable[[Any], _V] | None = None, fset: Callable[[Any, _V], None] | None = None, fdel: Callable[[Any], None] | None = None, *, name: str | None = None, label: str | None = None, annotation: Any = None, widget_type: type | str | None = None, auto_call: bool = False, layout: str = 'horizontal', call_button: bool | str | None = None, options: dict[str, Any] | None = None, record: bool = True)[source]

Bases: magicclass.fields._fields.MagicField[magicclass.fields._property._ButtonedWidget, magicclass.fields._property._V]

A property-like descriptor that returns a field for magicgui widgets.

For instance, the following code

>>> @magicproperty
>>> def x(self):
>>>     return self._x
>>> @x.setter
>>> def x(self, val: int):
>>>     self._x = val

will create a magicgui widget with a button "Set".

copy() Self[_V][source]

Copy object.

deleter(fdel: Callable[[Any], None]) magicclass.fields._property.magicproperty[magicclass.fields._property._V][source]

Define a deleter function.

classmethod from_setter(fset: Callable[[Any, _V], None] = None, *, name: str | None = None, label: str | None = None, annotation: Any = None, widget_type: type | str | None = None, auto_call: bool = False, layout: str = 'horizontal', call_button: bool | str | None = None, options: dict[str, Any] | None = None, record: bool = True) Self[_V][source]
get_widget(obj: Any) magicclass.fields._property._ButtonedWidget[source]

A light-weight version.

getter(fget: Callable[[Any], magicclass.fields._property._V]) magicclass.fields._property.magicproperty[magicclass.fields._property._V][source]

Define a getter function.

name: str
setter(fset: Callable[[Any, magicclass.fields._property._V], None]) magicclass.fields._property.magicproperty[magicclass.fields._property._V][source]

Define a setter function.

magicclass.magictoolbar(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon: Any | None = None)[source]

Decorator that converts a Python class into a menu bar.

magicclass.mark_on_called(function: Callable) Callable[[magicclass.wrappers._Fn], magicclass.wrappers._Fn][source]
magicclass.mark_on_calling(function: Callable) Callable[[magicclass.wrappers._Fn], magicclass.wrappers._Fn][source]
magicclass.mark_preview(function: Callable | None = None, text: str = 'Preview', auto_call: bool = False)

Define a preview of a function.

This decorator is useful for advanced magicgui creation. A "Preview" button appears in the bottom of the widget built from the input function and the decorated function will be called with the same arguments. Following example shows how to define a previewer that prints the content of the selected file.

>>> def func(self, path: Path):
...     ...
>>> @impl_preview(func)
>>> def _func_prev(self, path: Path):
...     with open(path, mode="r") as f:
...         print(f.read())
Parameters
  • function (callable, optional) -- To which function previewer will be defined. If not provided, the to-be- decorated function itself will be used as the preview function.

  • text (str, optional) -- Text of the preview button or checkbox.

  • auto_call (bool, default is False) -- Whether the preview function will be auto-called. If true, a check box will appear above the call button, and the preview function is auto-called during it is checked.

magicclass.nogui(method: magicclass.wrappers.F) magicclass.wrappers.F[source]

Wrapped method will not be converted into a widget.

magicclass.repeat(ui: magicclass._gui._base.MagicTemplate, index: int = - 1) None[source]

Repeat last operation on GUI using recorded macro.

Parameters
  • ui (MagicTemplate) -- Target magic-class widget.

  • index (int, default is -1) -- Which execution will be repeated. Any object that support list slicing can be used. By default the last operation will be repeated.

magicclass.set_design(width: int | None = None, height: int | None = None, min_width: int | None = None, min_height: int | None = None, max_width: int | None = None, max_height: int | None = None, text: str | None = None, icon: str | None = None, font_size: int | None = None, font_family: int | None = None, font_color: Color | None = None, background_color: Color | None = None, visible: bool | None = None) Callable[[type[T]], type[T]] | Callable[[F], F][source]

Change button/action design by calling setter when the widget is created.

Parameters
  • width (int, optional) -- Button width. Call button.width = width.

  • height (int, optional) -- Button height. Call button.height = height.

  • min_width (int, optional) -- Button minimum width. Call button.min_width = min_width.

  • min_height (int, optional) -- Button minimum height. Call button.min_height = min_height.

  • max_width (int, optional) -- Button maximum width. Call button.max_width = max_width.

  • max_height (int, optional) -- Button maximum height. Call button.max_height = max_height.

  • text (str, optional) -- Button text. Call button.text = text.

  • icon (str, optional) -- Path to icon file. min_width and min_height will be automatically set to the icon size if not given.

  • font_size (int, optional) -- Font size of the text.

  • visible (bool default is True) -- Button visibility.

magicclass.set_options(layout: str = 'vertical', labels: bool = True, call_button: bool | str | None = None, auto_call: bool = False, **options) Callable[[F], F][source]

Set MagicSignature to functions.

By decorating a method with this function, magicgui will create a widget with these options. These codes are similar in appearance.

# A magicgui way
@magicgui(a={...})
def func(a):
    ...

# A magicclass way
@magicclass
class A:
    @set_options(a={...})
    def func(self, a):
        ...
Parameters
  • layout (str, default is "vertical") -- The type of layout to use in FunctionGui. Must be one of {'horizontal', 'vertical'}.

  • labels (bool, default is True) -- Whether labels are shown in the FunctionGui.

  • call_button (bool or str, optional) -- If True, create an additional button that calls the original function when clicked. If a str, set the button text. If None (the default), it defaults to True when auto_call is False, and False otherwise.

  • auto_call (bool, optional) -- If True, changing any parameter in either the GUI or the widget attributes will call the original function with the current settings. by default False

  • options (dict) -- Parameter options.

magicclass.update_widget_state(ui: MagicTemplate, macro: Macro | str | None = None) None[source]

Update widget values based on a macro.

This helper function works similar to the update_widget method of FunctionGui. In most cases, this function will be used for restoring a state from a macro recorded before. Value changed signal will not be emitted within this operation.

Parameters
  • ui (MagicTemplate) -- Magic class instance.

  • macro (Macro or str, optional) -- An executable macro or string that dictates how GUI will be updated.

magicclass.vfield(obj: Any = <Undefined>, *, name: str | None = None, label: str | None = None, widget_type: str | type[WidgetProtocol] | None = None, options: dict[str, Any] = {}, record: bool = True) MagicValueField[Widget, Any][source]

Make a MagicValueField object.

>>> i = vfield(1)
>>> i = vfield(widget_type="Slider")

Unlike MagicField, value itself can be accessed.

>>> ui.i      # int is returned
>>> ui.i = 3  # set value to the widget.
Parameters
  • obj (Any, default is Undefined) -- Reference to determine what type of widget will be created. If Widget subclass is given, it will be used as is. If other type of class is given, it will used as type annotation. If an object (not type) is given, it will be assumed to be the default value.

  • name (str, optional) -- Name of the widget.

  • label (str, optional) -- Label of the widget.

  • widget_type (str, optional) -- Widget type. This argument will be sent to create_widget function.

  • options (dict, optional) -- Widget options. This parameter will be passed to the options keyword argument of create_widget.

  • record (bool, default is True) -- A magic-class specific parameter. If true, record value changes as macro.

Return type

MagicValueField

magicclass.widget_property(func: Callable[[...], magicclass.fields._fields._W]) magicclass.fields._fields.MagicValueField[magicclass.fields._fields._W, Any][source]

Create a widget property from a function.

Generally, this decorator will be used in line with HasFields trait. If a widget has to be initialized depending on the state of the instance, you can define a field using a method.

>>> class A(HasFields):
>>>     def __init__(self, max: int = 10):
>>>         self._max = max
>>>     @widget_property
>>>     def param(self):
>>>         return SpinBox(value=1, max=self._max)

In this example, param is a field object similar to those defined using vfield but has a variable argument max.

>>> a = A(max=20)
>>> a.param  # Out: 1
>>> a.param = 4  # OK
>>> a.widgets.param  # SpinBox with value=1 and max=20
Parameters

func (callable) -- Widget constructor function.

Returns

A field with given constructor.

Return type

MagicValueField