magicclass package

Subpackages

Submodules

magicclass.class_gui module

class magicclass.class_gui.ClassGuiBase(close_on_run, popup_mode, error_mode)[source]

Bases: magicclass._base.BaseGui

native: QWidget
magicclass.class_gui.make_gui(container: type[magicgui.widgets._bases.container_widget.ContainerWidget], no_margin: bool = True)[source]

Make a ClassGui class from a Container widget. Because GUI class inherits Container here, functions that need overriden must be defined here, not in ClassGuiBase.

magicclass.containers module

magicclass.containers.wrap_container(cls: type[C] = None, base: type = None) Callable | type[C][source]

Provide a wrapper for a new container widget with a new protocol.

magicclass.core module

magicclass.core.Bound(value: Any) _AnnotatedAlias[source]

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

Bases: magicclass.core._CallableClass

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

Bases: object

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

Bases: magicclass.core._CallableClass

class magicclass.core.WidgetType(value)[source]

Bases: enum.Enum

An enumeration.

button = 'button'
collapsible = 'collapsible'
list = 'list'
mainwindow = 'mainwindow'
none = 'none'
scrollable = 'scrollable'
split = 'split'
stacked = 'stacked'
tabbed = 'tabbed'
toolbox = 'toolbox'
magicclass.core.magicclass(class_: type | None = None, *, layout: str = 'vertical', labels: bool = True, name: str = None, close_on_run: bool = None, popup: bool = True, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, widget_type: str | WidgetType = WidgetType.none, parent=None) ClassGui[source]

Decorator that can convert a Python class into a widget.

..code-block:: python

@magicclass class C:

...

c = C(a=0) c.show()

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) -- Name of GUI.

  • 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.

  • 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: bool = True, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = 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: bool = True, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = 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.creator module

class magicclass.creator.Layout(value)[source]

Bases: enum.Enum

An enumeration.

horizontal = 1
vertical = 0
class magicclass.creator.MagicClassCreator[source]

Bases: magicgui.widgets._bases.widget.Widget, magicgui.widgets._bases.mixins._OrientationMixin, MutableSequence[magicgui.widgets._bases.widget.Widget]

magicclass.fields module

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

Bases: dataclasses.Field

Field class for magicgui construction. This object is compatible with dataclass.

property annotation
as_getter(obj: magicclass.fields.X)[source]

Make a function that get the value of Widget.

compare
connect(func: Callable) Callable[source]

Set callback function to "ready to connect" state.

default
default_factory
get_widget(obj: magicclass.fields.X) magicgui.widgets._bases.widget.Widget[source]

Get 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_widget() magicgui.widgets._bases.widget.Widget[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
class magicclass.fields.MagicValueField(default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, metadata: dict = {}, name: Optional[str] = None, record: bool = True)[source]

Bases: magicclass.fields.MagicField

callbacks: list[typing.Callable]
compare
default
default_factory
get_widget(obj: magicclass.fields.X) magicgui.widgets._bases.value_widget.ValueWidget[source]

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

guis: dict[int, ~X]
hash
init
metadata
name
repr
type
magicclass.fields.field(obj: Any = <dataclasses._MISSING_TYPE object>, *, name: str = '', widget_type: str | type[WidgetProtocol] | None = None, options: WidgetOptions = {}, record: bool = True) MagicField[source]

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: Any = <dataclasses._MISSING_TYPE object>, *, name: str = '', widget_type: str | type[WidgetProtocol] | None = None, options: WidgetOptions = {}, record: bool = True) MagicValueField[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 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.

Returns

Return type

MagicValueField

magicclass.macro module

class magicclass.macro.Expr(head: magicclass.macro.Head, args: Iterable[Any])[source]

Bases: object

Python expression class. Inspired by Julia (https://docs.julialang.org/en/v1/manual/metaprogramming/), this class enables efficient macro recording and macro operation.

Expr objects are mainly composed of "head" and "args". "Head" denotes what kind of operation it is, and "args" denotes the arguments needed for the operation. Other attributes, such as "symbol", is not necessary as a Expr object but it is useful to create executable codes.

classmethod convert_args(args: tuple[Any, ...], kwargs: dict[str | Symbol, Any]) list[source]
copy()[source]
eval(_globals: dict[magicclass.macro.Symbol, typing.Any] = {}, _locals: dict[magicclass.macro.Symbol, typing.Any] = {})[source]
format(mapping: dict[Symbol, Symbol | Expr], inplace: bool = False) Expr[source]
iter_args() Iterator[magicclass.macro.Symbol][source]

Recursively iterate along all the arguments.

iter_expr() Iterator[magicclass.macro.Expr][source]

Recursively iterate over all the nested Expr, until it reached to non-nested Expr. This method is useful in macro generation.

iter_values() Iterator[magicclass.macro.Expr][source]

Recursively iterate along all the values.

n: int = 0
classmethod parse(a: Any) magicclass.macro.Expr[source]
classmethod parse_call(func: Callable, args: Optional[tuple[typing.Any, ...]] = None, kwargs: Optional[dict[str, typing.Any]] = None) magicclass.macro.Expr[source]

Make a function call expression. Expression: func(*args, **kwargs)

classmethod parse_init(obj: Any, init_cls: type, args: Optional[tuple[typing.Any, ...]] = None, kwargs: Optional[dict[str, typing.Any]] = None) magicclass.macro.Expr[source]
classmethod parse_method(obj: Any, func: Callable, args: tuple[typing.Any, ...], kwargs: dict[str, typing.Any]) magicclass.macro.Expr[source]

Make a method call expression. Expression: obj.func(*args, **kwargs)

class magicclass.macro.Head(value)[source]

Bases: enum.Enum

An enumeration.

assign = 'assign'
call = 'call'
comment = 'comment'
getattr = 'getattr'
getitem = 'getitem'
init = 'init'
kw = 'kw'
value = 'value'
class magicclass.macro.Macro(iterable: Iterable = (), *, active: bool = True)[source]

Bases: collections.UserList

List with pretty output customized for macro.

append(_Macro__object: magicclass.macro.Expr)[source]

S.append(value) -- append value to the end of the sequence

context(active: bool)[source]
record(function=None, *, returned_callback: Optional[Callable[[magicclass.macro.Expr], magicclass.macro.Expr]] = None)[source]
class magicclass.macro.Symbol(seq: str, object_id: Optional[int] = None, type: type = typing.Any)[source]

Bases: object

as_parameter(default)[source]
classmethod register_type(type: type[~ T], function: Callable[[magicclass.macro.T], str])[source]
magicclass.macro.register_type(type: type[~ T], function: Callable[[magicclass.macro.T], str])[source]
magicclass.macro.symbol(obj: Any) magicclass.macro.Symbol[source]

magicclass.menu_gui module

class magicclass.menu_gui.ContextMenuGui(parent=None, name: str = None, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None)[source]

Bases: magicclass.menu_gui.MenuGuiBase

Magic class that will be converted into a context menu.

class magicclass.menu_gui.MenuGui(parent=None, name: str = None, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None)[source]

Bases: magicclass.menu_gui.MenuGuiBase

Magic class that will be converted into a menu bar.

class magicclass.menu_gui.MenuGuiBase(parent=None, name: str = None, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None)[source]

Bases: magicclass._base.BaseGui

append(obj: Callable | MenuGuiBase | Action | Separator | Container)[source]
property parent

magicclass.mgui_ext module

class magicclass.mgui_ext.Action(*args, name: Optional[str] = None, text: Optional[str] = None, gui_only: bool = True, **kwargs)[source]

Bases: object

QAction encapsulated class with a similar API as magicgui Widget.

changed
property enabled
from_options(options: dict[str] | Callable)[source]
property icon_path
property name: str
property running: bool
property text: str
property tooltip: str
property value
property visible
class magicclass.mgui_ext.FunctionGuiPlus(function: Callable[..., _R], call_button: bool | str | None = None, layout: str = 'vertical', labels: bool = True, tooltips: bool = True, app: AppRef = None, visible: bool = None, auto_call: bool = False, result_widget: bool = False, param_options: dict[str, dict] | None = None, name: str = None, persist: bool = False, **kwargs)[source]

Bases: magicgui.widgets.Container, Generic[magicgui.widgets._function_gui._R]

FunctionGui class with a parameter recording functionality etc.

insert(key: int, widget: magicgui.widgets._bases.widget.Widget)[source]

Insert widget at key.

class magicclass.mgui_ext.PushButtonPlus(text: str | None = None, **kwargs)[source]

Bases: magicgui.widgets.PushButton

A Qt specific PushButton widget with a magicgui bound.

property background_color
property font_color
property font_family
property font_size
from_options(options: dict[str] | Callable)[source]
property icon_path
property icon_size
property running: bool

magicclass.signature module

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(self: inspect.Signature | MagicSignature)[source]
magicclass.signature.upgrade_signature(func, gui_options: Optional[dict] = None, caller_options: Optional[dict] = None, additional_options: Optional[dict] = 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 (dict, optional) -- Additional options that will be used in magic class.

Returns

Same function with upgraded signature

Return type

callable

magicclass.utils module

exception magicclass.utils.InvalidMagicClassError[source]

Bases: Exception

This exception will be raised when class definition is not a valid magic-class.

magicclass.utils.check_collision(cls0: type, cls1: type)[source]

Check if two classes have name collisions.

magicclass.utils.define_callback(self, callback: Callable)[source]
magicclass.utils.extract_tooltip(obj: Any) str[source]
magicclass.utils.get_app()[source]

Get QApplication. This is important when using Jupyter.

magicclass.utils.get_parameters(fgui: FunctionGui)[source]
magicclass.utils.get_signature(func)[source]
magicclass.utils.getmembers(object: type, exclude_prefix: str)[source]

This function is identical to inspect.getmembers except for the order of the results. We have to sort the name in the order of line number.

magicclass.utils.gui_qt()[source]

Call "%gui qt" magic,

magicclass.utils.identity_wrapper(_func: Callable, parent: Widget = None)[source]

Do nothing.

magicclass.utils.iter_members(cls: type, exclude_prefix: str = '__') list[str, typing.Any][source]

Iterate over all the members in the order of source code line number.

magicclass.utils.n_parameters(func: Callable)[source]

Count the number of parameters of a callable object.

magicclass.utils.raise_error_in_msgbox(_func: Callable, parent: Widget = None)[source]

If exception happened inside function, then open a message box.

magicclass.utils.screen_center()[source]

Get the center coordinate of the screen.

magicclass.wrappers module

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.do_not_record(method: Callable)[source]

Wrapped method will not be recorded in macro.

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[str, Iterable[float]]] = None, background_color: Optional[Union[str, Iterable[float]]] = 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(**options)[source]

Set MagicSignature to functions. By decorating a function like below:

>>> @set_options(x={"value": -1})
>>> def func(x):
>>>     ...

then magicgui knows what widget it should be converted to.

Module contents