Skip to content

Commit

Permalink
resolve ForwardRef on widget.annotation (#66)
Browse files Browse the repository at this point in the history
* resolve ForwardRef on widget.annotation

* return annotation
  • Loading branch information
tlambert03 committed Dec 27, 2020
1 parent 510d5ef commit c441861
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
17 changes: 17 additions & 0 deletions magicgui/widgets/_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def __init__(
TYPE_CHECKING,
Any,
Callable,
ForwardRef,
List,
MutableSequence,
Optional,
Expand Down Expand Up @@ -244,6 +245,22 @@ def __init__(
if not visible:
self.hide()

@property
def annotation(self):
"""Return type annotation for the parameter represented by the widget.
ForwardRefs will be resolve when setting the annotation.
"""
return self._annotation

@annotation.setter
def annotation(self, value):
if isinstance(value, ForwardRef):
from magicgui.type_map import _evaluate_forwardref

value = _evaluate_forwardref(value)
self._annotation = value

@property
def param_kind(self) -> inspect._ParameterKind:
"""Return :attr:`inspect.Parameter.kind` represented by this widget.
Expand Down
11 changes: 11 additions & 0 deletions tests/test_widgets.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
from tests import MyInt

from magicgui import magicgui, widgets

Expand Down Expand Up @@ -33,3 +34,13 @@ def test_delete_widget():
# they disappear from the layout
with pytest.raises(ValueError):
container.index(a)


def test_widget_resolves_forward_ref():
"""The annotation on a widget should always be a resolved type."""

@magicgui
def widget(x: "tests.MyInt"): # type: ignore # noqa
pass

assert widget.x.annotation is MyInt

0 comments on commit c441861

Please sign in to comment.