magicclass package

Subpackages

Submodules

magicclass.core module

class magicclass.core.MagicClassFactory(name: str, layout: str = 'vertical', labels: bool = True, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, widget_type: str | WidgetType = WidgetType.none, icon_path: str = None, parent=None, attrs: dict[str] = None)[source]

Bases: object

Factory class that can make any magic-class.

as_magicclass() magicclass.gui.class_gui.ClassGuiBase[source]
as_magiccontext() magicclass.gui.menu_gui.ContextMenuGui[source]
as_magicmenu() magicclass.gui.menu_gui.MenuGui[source]
as_magictoolbar() magicclass.gui.toolbar.ToolBarGui[source]
class magicclass.core.Parameters[source]

Bases: object

as_dict() dict[str, typing.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_path: str = None, stylesheet: str | StyleSheet = None, parent=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_path (str, optional) -- Path to the icon image.

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

  • parent (magicgui.widgets._base.Widget, optional) -- Parent widget if exists.

Returns

Return type

Decorated class or decorator.

magicclass.core.magiccontext(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_path: str = None, parent=None)[source]

Decorator that can convert a Python class into a context menu.

Parameters
  • class (type, optional) -- Class to be decorated.

  • 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) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.

  • parent (magicgui.widgets._base.Widget, optional) -- Parent widget if exists.

Returns

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_path: str = None, parent=None)[source]

Decorator that can convert a Python class into a menu bar.

Parameters
  • class (type, optional) -- Class to be decorated.

  • 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) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.

  • parent (magicgui.widgets._base.Widget, optional) -- Parent widget if exists.

Returns

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_path: str = None, parent=None)[source]

Decorator that can convert a Python class into a menu bar.

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

magicclass.fields module

class magicclass.fields.MagicField(default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, metadata: dict[str, Any] = {}, name: str | None = None, record: bool = True)[source]

Bases: dataclasses.Field, Generic[magicclass.fields._W, magicclass.fields._V]

Field class for magicgui construction.

This object is compatible with dataclass. MagicField object is in "ready for widget construction" state.

property annotation
as_getter(obj: Any) Callable[[Any], magicclass.fields._V][source]

Make a function that get the value of Widget or Action.

compare
connect(func: Callable) Callable[source]

Set callback function to "ready to connect" state.

copy() magicclass.fields.MagicField[source]

Copy object.

default
default_factory
disconnect(func: Callable) None[source]

Disconnect callback from the field. This method does NOT disconnect callbacks from widgets that are already created.

get_action(obj: Any) AbstractAction[source]

Get an action from obj. This function will be called every time MagicField is referred by obj.field.

get_widget(obj: Any) magicclass.fields._W[source]

Get a widget from obj. This function will be called every time MagicField is referred by obj.field.

hash
init
metadata
name
not_ready() bool[source]
property options: dict
ready() bool[source]
repr
to_action() Action | WidgetAction[_W][source]

Create a menu action or a menu widget action from the field.

Returns

Object that can be added to menu.

Return type

Action or WidgetAction

Raises

ValueError -- If there is not enough information to build an action.

to_widget() magicclass.fields._W[source]

Create a widget from the field.

Returns

Widget object that is ready to be inserted into Container.

Return type

Widget

Raises

ValueError -- If there is not enough information to build a widget.

type
property value: Any
property widget_type: str
wraps(method: Callable | None = None, *, template: Callable | None = None, copy: bool = False)[source]

Call the wraps class method of magic class.

This method is needed when a child magic class is defined outside the main magic class, and integrated into the main magic class by field function, like below

@magicclass
class B:
    def func(self): ...  # pre-definition

@magicclass
class A:
    b = field(B)

    @b.wraps
    def func(self):
        # do something
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.fields.MagicValueField(default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, metadata: dict[str, Any] = {}, name: str | None = None, record: bool = True)[source]

Bases: magicclass.fields.MagicField[magicclass.fields._W, magicclass.fields._V]

Field class for magicgui construction. Unlike MagicField, object of this class always returns value itself.

callbacks: list[Callable]
compare
default
default_factory
get_widget(obj: Any) magicclass.fields._W[source]

Get a widget from obj. This function will be called every time MagicField is referred by obj.field.

guis: dict[int, _M]
hash
init
metadata
name
parent_class: type
repr
type
magicclass.fields.field(obj: magicclass.fields._X, *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X][source]
magicclass.fields.field(obj: type[~ _W], *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicclass.fields._W, Any]
magicclass.fields.field(obj: type[~ _X], *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X]
magicclass.fields.field(obj: type[_M], *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') MagicField[_M, Any]
magicclass.fields.field(obj: Any, *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicgui.widgets._bases.widget.Widget, Any]

Make a MagicField object.

>>> i = field(1)
>>> i = field(widget_type="Slider")
Parameters
  • obj (Any, default is MISSING) -- 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, default is "") -- Name 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 always be used in widget(**options) form.

  • record (bool, default is True) -- Record value changes as macro.

Returns

Return type

MagicField

magicclass.fields.vfield(obj: magicclass.fields._X, *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X][source]
magicclass.fields.vfield(obj: type[~ _W], *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicclass.fields._W, Any]
magicclass.fields.vfield(obj: type[~ _X], *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X]
magicclass.fields.vfield(obj: Any, *, name: str = "''", widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicgui.widgets._bases.widget.Widget, Any]

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 MISSING) -- 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, default is "") -- Name of the widget.

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

  • options (WidgetOptions, optional) --

  • record (bool, default is True) -- Record value changes as macro.

Returns

Return type

MagicValueField

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.qthreading module

class magicclass.qthreading.Callbacks[source]

Bases: object

List of callback functions.

property callbacks: tuple[typing.Callable, ...]
connect(callback: magicclass.qthreading._F) magicclass.qthreading._F[source]

Append a callback function to the callback list.

Parameters

callback (Callable) -- Callback function.

disconnect(callback: magicclass.qthreading._F) magicclass.qthreading._F[source]

Remove callback function from the callback list.

Parameters

callback (Callable) -- Callback function to be removed.

class magicclass.qthreading.NapariProgressBar(value: int = 0, max: int = 1000)[source]

Bases: object

A progressbar class that provides napari progress bar with same API.

close()[source]
property label: str
property max: int
show()[source]
property value: int
property visible: bool
magicclass.qthreading.close_pbar(pbar: Union[magicgui.widgets.ProgressBar, magicclass.qthreading.NapariProgressBar])[source]

Close progressbar.

magicclass.qthreading.increment(pbar: Union[magicgui.widgets.ProgressBar, magicclass.qthreading.NapariProgressBar])[source]

Increment progressbar.

magicclass.qthreading.init_pbar(pbar: Union[magicgui.widgets.ProgressBar, magicclass.qthreading.NapariProgressBar])[source]

Initialize progressbar.

class magicclass.qthreading.thread_worker(f: Callable | None = None, *, ignore_errors: bool = False, progress: dict[str, Any] | None = None)[source]

Bases: object

Create a worker in a superqt/napari style.

property aborted: magicclass.qthreading.Callbacks

Event that will be emitted on aborted.

property errored: magicclass.qthreading.Callbacks

Event that will be emitted on errored.

property finished: magicclass.qthreading.Callbacks

Event that will be emitted on finished.

property not_ready: bool
property returned: magicclass.qthreading.Callbacks

Event that will be emitted on returned.

property started: magicclass.qthreading.Callbacks

Event that will be emitted on started.

property yielded: magicclass.qthreading.Callbacks

Event that will be emitted on yielded.

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

class magicclass.tqdm.ProgressBar(name: str = '', annotation: Any = None, label: str = None, tooltip: str | None = None, visible: bool | None = None, enabled: bool = True, gui_only=False, backend_kwargs={}, value: Any = UNSET, bind: Any = UNSET, nullable=False, min: float = 0, max: float = 1000, step: float = 1, orientation: str = 'horizontal', readout: bool = True, tracking: bool = True)[source]

Bases: magicgui.widgets.ProgressBar

tqdm(iterable=None, *args, **kwargs)[source]
trange(*args, **kwargs)[source]
class magicclass.tqdm.tqdm(*_, **__)[source]

Bases: tqdm.std.tqdm

Re-implementation of magicgui's tqdm.

close() None[source]

Cleanup and (if leave=False) close the progressbar.

disable: bool
display(msg: Optional[str] = None, pos: Optional[int] = None) None[source]

Update the display.

magicclass.tqdm.trange(*args, **kwargs) magicclass.tqdm.tqdm[source]

Shortcut for tqdm(range(*args), **kwargs).

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}].

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

Bases: object

Make Annotated type similar to typing.List.

Arguments annotated with List[...] will create a ListEdit with a annotated sub types.

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.

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

Bases: object

Make Annotated type similar to typing.Tuple.

Arguments annotated with Tuple[...] will create a TupleEdit with a annotated sub types.

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.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.Canceled[source]

Bases: RuntimeError

Raised when a function is canceled

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.click(enables: Optional[Union[str, Iterable[str]]] = None, disables: Optional[Union[str, Iterable[str]]] = None, enabled: bool = True, shows: Optional[Union[str, Iterable[str]]] = None, hides: Optional[Union[str, Iterable[str]]] = None, visible: bool = True)[source]

Set options of push buttons related to button clickability.

Parameters
  • enables (str or iterable of str, optional) -- Enables other button(s) in this list when clicked.

  • disables (str or iterable of str, optional) -- Disables other button(s) in this list when clicked.

  • enabled (bool, default is True) -- The initial clickability state of the button.

  • shows (str or iterable of str, optional) -- Make other button(s) in this list visible when clicked.

  • hides (str or iterable of str, optional) -- Make other button(s) in this list invisible when clicked.

  • visible (bool, default is True) -- The initial visibility of the button.

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

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

Wrapped method will not be recorded in macro.

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: Optional[int] = None, height: Optional[int] = None, min_width: Optional[int] = None, min_height: Optional[int] = None, max_width: Optional[int] = None, max_height: Optional[int] = None, text: Optional[str] = None, icon_path: Optional[str] = None, icon_size: Optional[tuple[int, int]] = None, font_size: Optional[int] = None, font_family: Optional[int] = None, font_color: Optional[Union[Iterable[float], str]] = None, background_color: Optional[Union[Iterable[float], str]] = None, visible: bool = True)[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_path (str, optional) -- Path to icon file. min_width and min_height will be automatically set to the icon size if not given.

  • icon_size (tuple of two int, optional) -- Icon size.

  • 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