Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested pydantic model containers #669

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

**Fixed bugs:**

- fix: Fix checking sublcasses of Future [\#665](https://github.com/pyapp-kit/magicgui/pull/665) ([Czaki](https://github.com/Czaki))
- fix: Fix checking subclasses of Future [\#665](https://github.com/pyapp-kit/magicgui/pull/665) ([Czaki](https://github.com/Czaki))

## [v0.9.0](https://github.com/pyapp-kit/magicgui/tree/v0.9.0) (2024-08-05)

Expand Down
4 changes: 3 additions & 1 deletion src/magicgui/schema/_guiclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

from typing_extensions import TypeGuard

from magicgui.types import NestedValueWidgets

# fmt: off
class GuiClassProtocol(Protocol):
"""Protocol for a guiclass."""
Expand Down Expand Up @@ -206,7 +208,7 @@ def __set_name__(self, owner: type, name: str) -> None:

def __get__(
self, instance: object | None, owner: type
) -> ContainerWidget[ValueWidget]:
) -> ContainerWidget[NestedValueWidgets]:
wdg = build_widget(owner if instance is None else instance)

# look for @button-decorated methods
Expand Down
27 changes: 22 additions & 5 deletions src/magicgui/schema/_ui_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from attrs import Attribute
from pydantic.fields import FieldInfo, ModelField

from magicgui.types import NestedValueWidgets
from magicgui.widgets.bases import ContainerWidget, ValueWidget

class HasAttrs(Protocol):
Expand All @@ -45,7 +46,6 @@
SLOTS = {"slots": True} if sys.version_info >= (3, 10) else {}
T = TypeVar("T")


@dataclass(frozen=True, **SLOTS)
class UiField(Generic[T]):
"""Metadata about a specific widget in a GUI."""
Expand Down Expand Up @@ -394,7 +394,9 @@
kwargs.pop("name", None)
return dc.replace(self, **kwargs)

def create_widget(self, value: T | _Undefined = Undefined) -> ValueWidget[T]:
def create_widget(self,
value: T | _Undefined = Undefined
) -> ValueWidget[T] | NestedValueWidgets:
"""Create a new Widget for this field."""
from magicgui.type_map import get_widget_class

Expand Down Expand Up @@ -441,7 +443,20 @@
opts["min"] = d["exclusive_minimum"] + m

value = value if value is not Undefined else self.get_default() # type: ignore
cls, kwargs = get_widget_class(value=value, annotation=self.type, options=opts)
try:
cls, kwargs = get_widget_class(
value=value, annotation=self.type, options=opts
)
except ValueError:
try:
wdg = build_widget(self.type)
wdg.label = self.name if self.name else ""
return wdg
except TypeError as e:
raise TypeError(

Check warning on line 456 in src/magicgui/schema/_ui_field.py

View check run for this annotation

Codecov / codecov/patch

src/magicgui/schema/_ui_field.py#L450-L456

Added lines #L450 - L456 were not covered by tests
f"Could not create widget for field {self.name!r} "
f"with value {value!r}"
) from e
return cls(**kwargs) # type: ignore


Expand Down Expand Up @@ -786,7 +801,7 @@
values: Mapping[str, Any] | None = None,
*,
container_kwargs: Mapping | None = None,
) -> ContainerWidget[ValueWidget]:
) -> ContainerWidget[NestedValueWidgets]:
"""Create a container widget from a sequence of UiFields.

This function is the heart of build_widget.
Expand Down Expand Up @@ -849,7 +864,9 @@


# TODO: unify this with magicgui
def build_widget(cls_or_instance: Any) -> ContainerWidget[ValueWidget]:
def build_widget(
cls_or_instance: Any
) -> ContainerWidget[NestedValueWidgets]:
"""Build a magicgui widget from a dataclass, attrs, pydantic, or function."""
values = None if isinstance(cls_or_instance, type) else _get_values(cls_or_instance)
return _uifields_to_container(get_ui_fields(cls_or_instance), values=values)
10 changes: 9 additions & 1 deletion src/magicgui/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@

if TYPE_CHECKING:
from magicgui.widgets import FunctionGui
from magicgui.widgets.bases import CategoricalWidget, Widget
from magicgui.widgets.bases import (
CategoricalWidget,
ContainerWidget,
ValueWidget,
Widget,
)
from magicgui.widgets.protocols import WidgetProtocol


Expand All @@ -28,6 +33,9 @@ class ChoicesDict(TypedDict):
WidgetRef = Union[str, WidgetClass]
#: A :attr:`WidgetClass` (or a string representation of one) and a dict of kwargs
WidgetTuple = Tuple[WidgetRef, Dict[str, Any]]
#: A [`ValueWidget`][magicgui.widgets.ValueWidget] class or a
#: [`ContainerWidget`][magicgui.widgets.ContainerWidget] class for nesting those
NestedValueWidgets = Union["ValueWidget", "ContainerWidget[NestedValueWidgets]"]
#: An iterable that can be used as a valid argument for widget ``choices``
ChoicesIterable = Union[Iterable[Tuple[str, Any]], Iterable[Any]]
#: An callback that can be used as a valid argument for widget ``choices``. It takes
Expand Down
12 changes: 7 additions & 5 deletions src/magicgui/widgets/bases/_container_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,13 @@

def asdict(self) -> dict[str, Any]:
"""Return state of widget as dict."""
return {
w.name: getattr(w, "value", None)
for w in self._list
if w.name and not w.gui_only
}
ret = {}
for w in self._list:
if w.name and not w.gui_only:
ret[w.name] = getattr(w, "value", None)
if isinstance(w, ContainerWidget) and w.widget_type == "Container":
ret[w.label] = w.asdict()

Check warning on line 343 in src/magicgui/widgets/bases/_container_widget.py

View check run for this annotation

Codecov / codecov/patch

src/magicgui/widgets/bases/_container_widget.py#L343

Added line #L343 was not covered by tests
return ret

def update(
self,
Expand Down
Loading