Skip to content

Commit

Permalink
Add basic implementation of type-hint-based interact
Browse files Browse the repository at this point in the history
  • Loading branch information
corranwebster committed Apr 17, 2024
1 parent b78de43 commit 5664ef7
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions python/ipywidgets/ipywidgets/widgets/interaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@
"""Interact with functions using widgets."""

from collections.abc import Iterable, Mapping
from enum import EnumType
from inspect import signature, Parameter
from inspect import getcallargs
from inspect import getfullargspec as check_argspec
import sys

from IPython import get_ipython
from . import (Widget, ValueWidget, Text,
FloatSlider, IntSlider, Checkbox, Dropdown,
VBox, Button, DOMWidget, Output)
FloatSlider, FloatText, IntSlider, IntText, Checkbox,
Dropdown, VBox, Button, DOMWidget, Output)
from IPython.display import display, clear_output
from traitlets import HasTraits, Any, Unicode, observe
from numbers import Real, Integral
Expand Down Expand Up @@ -125,6 +126,8 @@ def _yield_abbreviations_for_parameter(param, kwargs):
value = kwargs.pop(name)
elif default is not empty:
value = default
elif param.annotation:
value = param.annotation
else:
yield not_found
yield (name, value, default)
Expand Down Expand Up @@ -304,6 +307,12 @@ def widget_from_abbrev(cls, abbrev, default=empty):
# ignore failure to set default
pass
return widget

# Try type annotation
if isinstance(abbrev, type):
widget = cls.widget_from_annotation(abbrev)
if widget is not None:
return widget

# Try single value
widget = cls.widget_from_single_value(abbrev)
Expand Down Expand Up @@ -341,6 +350,22 @@ def widget_from_single_value(o):
else:
return None

@staticmethod
def widget_from_annotation(t):
"""Make widgets from type annotation and optional default value."""
if t is str:
return Text()
elif t is bool:
return Checkbox()
elif t in {int, Integral}:
return IntText()
elif t in {float, Real}:
return FloatText()
elif isinstance(t, EnumType):
return Dropdown(options={option.name: option for option in t})
else:
return None

@staticmethod
def widget_from_tuple(o):
"""Make widgets from a tuple abbreviation."""
Expand Down

0 comments on commit 5664ef7

Please sign in to comment.