Skip to content

Commit

Permalink
Implement TypeMap to enable module specific type map registration (#…
Browse files Browse the repository at this point in the history
…677)

* implement TypeMap

* update tests

* fix py39 and pint
  • Loading branch information
hanjinliu authored Nov 9, 2024
1 parent 674094f commit a5669e3
Show file tree
Hide file tree
Showing 10 changed files with 1,110 additions and 923 deletions.
28 changes: 21 additions & 7 deletions src/magicgui/signature.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from typing_extensions import Unpack

from magicgui.application import AppRef
from magicgui.type_map import TypeMap
from magicgui.widgets import Container, Widget
from magicgui.widgets.bases._container_widget import ContainerKwargs

Expand Down Expand Up @@ -189,12 +190,18 @@ def __str__(self) -> str:
)
)

def to_widget(self, app: AppRef | None = None) -> Widget:
def to_widget(
self,
app: AppRef | None = None,
type_map: TypeMap | None = None,
) -> Widget:
"""Create and return a widget for this object."""
from magicgui.widgets import create_widget
from magicgui.type_map import TypeMap

value = Undefined if self.default in (self.empty, TZ_EMPTY) else self.default
widget = create_widget(
if type_map is None:
type_map = TypeMap.global_instance()
widget = type_map.create_widget(
name=self.name,
value=value,
annotation=self.annotation,
Expand Down Expand Up @@ -287,19 +294,26 @@ def from_signature(
raise_on_unknown=raise_on_unknown,
)

def widgets(self, app: AppRef | None = None) -> MappingProxyType:
def widgets(
self,
app: AppRef | None = None,
type_map: TypeMap | None = None,
) -> MappingProxyType:
"""Return mapping from parameters to widgets for all params in Signature."""
return MappingProxyType(
{n: p.to_widget(app) for n, p in self.parameters.items()}
{n: p.to_widget(app, type_map=type_map) for n, p in self.parameters.items()}
)

def to_container(
self, app: AppRef | None = None, **kwargs: Unpack[ContainerKwargs]
self,
app: AppRef | None = None,
type_map: TypeMap | None = None,
**kwargs: Unpack[ContainerKwargs],
) -> Container:
"""Return a ``magicgui.widgets.Container`` for this MagicSignature."""
from magicgui.widgets import Container

kwargs["widgets"] = list(self.widgets(app).values())
kwargs["widgets"] = list(self.widgets(app, type_map=type_map).values())
return Container(**kwargs)

def replace( # type: ignore[override]
Expand Down
9 changes: 8 additions & 1 deletion src/magicgui/type_map/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
"""Functions that map python types to widgets."""

from ._type_map import get_widget_class, register_type, type2callback, type_registered
from ._type_map import (
TypeMap,
get_widget_class,
register_type,
type2callback,
type_registered,
)

__all__ = [
"get_widget_class",
"register_type",
"type_registered",
"type2callback",
"TypeMap",
]
Loading

0 comments on commit a5669e3

Please sign in to comment.