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)[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.

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: 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: FreeWidget

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

Bases: 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.signature module

class magicclass.signature.AdditionalOptions[source]

Bases: TypedDict

copyto: str
gui: bool
into: str
keybinding: str
moveto: str
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: 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: Signature, gui_options=None, caller_options=None, additional_options=None) MagicMethodSignature[source]

Convert regular inspect.Signature to MagicSignature.

classmethod get_gui_options(sig: inspect.Signature | MagicSignature) WidgetOptions[source]
replace(*, parameters=<class 'magicclass.signature._void'>, return_annotation: ~typing.Any = <class 'magicclass.signature._void'>) 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.upgrade_signature(func, gui_options: Optional[dict] = None, caller_options: Optional[WidgetOptions] = None, additional_options: Optional[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 (WidgetOptions, 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 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.

Examples

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.WidgetType(value)[source]

Bases: 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[[_W], _V]) type[_V][source]
magicclass.types.bound(obj: Callable[[Any, _W], _V]) type[_V]
magicclass.types.bound(obj: MagicField[_W, _V]) type[_V]
magicclass.types.bound(obj: type[_W]) type

Function version of Bound[...].

magicclass.wrappers module

exception magicclass.wrappers.Canceled[source]

Bases: RuntimeError

Raised when a function is canceled

magicclass.wrappers.bind_key(*key) Callable[[F], 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[[F], F][source]
magicclass.wrappers.confirm(f: F, *, text: str | None, condition: Callable[..., bool] | str | None, callback: Callable[[str, BaseGui], None] | None = None) 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: F) F[source]

Wrapped method will not be recorded in macro.

magicclass.wrappers.mark_preview(function: Callable, text: str = 'Preview') Callable[[F], F][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):
    ...

@mark_preview(func)
def _func_prev(self, path: Path):
    with open(path, mode="r") as f:
        print(f.read())
Parameters
  • function (callable) -- To which function previewer will be defined.

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

magicclass.wrappers.nogui(method: F) 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: Container, HasFields, _FieldObject

property callbacks: tuple[Callable, ...]

Return callbacks in an immutable way.

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

Copy widget.

get_widget(obj) 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: SignalView

Return a view of signals.

property widgets: WidgetView

Return a view of widgets.

class magicclass.Icon[source]

Bases: 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

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: object

annotation: Any
append(widget: Widget) None[source]
changed: Signal
close() None[source]
enabled: bool
find_ancestor(ancestor: type[_T]) _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.

Returns

Magic class object if found.

Return type

MagicTemplate

gui_only: bool
height: int
hide() None[source]
icon: Any
index(value: Any, start: int, stop: int) int[source]
insert(key: int, widget: Widget) None[source]
label: str
label_changed: Signal
labels: bool
layout: str
property 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.

remove(value: Widget | str)[source]
render() np.ndarray[source]
reset_choices(*args)[source]
show(run: bool) None[source]
tooltip: str
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

Define how to popup FunctionGui.

above = 'above'
below = 'below'
dialog = 'dialog'
dock = 'dock'
first = 'first'
last = 'last'
parentlast = 'parentlast'
parentsub = 'parentsub'
popup = 'popup'
magicclass.bind_key(*key) Callable[[F], 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: F) F[source]

Wrapped method will not be recorded in macro.

magicclass.field(obj: Any = UNSET, *, name: str | None = None, label: str | None = None, widget_type: str | type[WidgetProtocol] | None = None, options: dict[str, Any] = {}, record: bool = True) MagicField[Widget, Any][source]

Make a MagicField object.

>>> i = field(1)
>>> i = field(widget_type="Slider")
Parameters
  • obj (Any, default is UNSET) -- 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 (WidgetOptions, 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.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)[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.

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.

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_preview(function: Callable, text: str = 'Preview') Callable[[F], F][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):
    ...

@mark_preview(func)
def _func_prev(self, path: Path):
    with open(path, mode="r") as f:
        print(f.read())
Parameters
  • function (callable) -- To which function previewer will be defined.

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

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

Wrapped method will not be converted into a widget.

magicclass.repeat(ui: 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 = UNSET, *, 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 UNSET) -- 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 (WidgetOptions, 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[[...], _W]) MagicValueField[_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

magicclass.wraps(template: Callable | inspect.Signature) Callable[[_C], _C][source]

Update signature using a template. If class is wrapped, then all the methods except for those start with "__" will be wrapped.

Parameters

template (Callable or inspect.Signature object) -- Template function or its signature.

Returns

A wrapper which take a function or class as an input and returns same function or class with updated signature(s).

Return type

Callable