@@ -185,28 +185,45 @@ def wrapper(fn: Union[IPyWidgetRenderFunc, IPyWidgetRenderFuncAsync]) -> IPyWidg
185185 return wrapper
186186
187187
188- # altair objects aren't directly renderable as an ipywidget,
189- # but we can still render them as an ipywidget via ipyvega
190- # TODO: we should probably do this for bokeh, pydeck, and probably others as well
188+ # altair/pydeck/bokeh objects aren't directly renderable as an ipywidget,
189+ # but we can coerce them into one
191190def _as_widget (x : object ) -> Widget :
192- if widget_pkg (x ) == "altair" :
191+ pkg = widget_pkg (x )
192+ if pkg == "altair" and not isinstance (x , Widget ):
193193 try :
194194 import altair
195195 from vega .widget import VegaWidget
196196
197197 x = cast (altair .Chart , x )
198198 x = VegaWidget (x .to_dict ()) # type: ignore
199199 except ImportError :
200- raise ImportError ("ipyvega is required to render altair charts" )
201- elif widget_pkg (x ) == "pydeck" :
202- import pydeck
200+ raise ImportError (
201+ "To render altair charts, the ipyvega package must be installed."
202+ )
203+ except Exception as e :
204+ raise RuntimeError (f"Failed to coerce { x } into a VegaWidget: { e } " )
203205
204- if isinstance (x , pydeck .Deck ):
206+ elif pkg == "pydeck" and not isinstance (x , Widget ):
207+ try :
205208 from pydeck .widget import DeckGLWidget
206209
207- x_ = x .to_json ()
210+ x_ = x .to_json () # type: ignore
208211 x = DeckGLWidget ()
209212 x .json_input = x_
213+ except Exception as e :
214+ raise RuntimeError (f"Failed to coerce { x } into a DeckGLWidget: { e } " )
215+
216+ elif pkg == "bokeh" and not isinstance (x , Widget ):
217+ try :
218+ from jupyter_bokeh import BokehModel
219+
220+ x = BokehModel (x ) # type: ignore
221+ except ImportError :
222+ raise ImportError (
223+ "To render bokeh charts, the jupyter_bokeh package must be installed."
224+ )
225+ except Exception as e :
226+ raise RuntimeError (f"Failed to coerce { x } into a BokehModel: { e } " )
210227
211228 if isinstance (x , Widget ):
212229 return x
0 commit comments