Skip to content

Instantly share code, notes, and snippets.

@CatChenal
Last active August 8, 2023 15:24
Show Gist options
  • Save CatChenal/39190d080f3aed62c3a559119c24ab4a to your computer and use it in GitHub Desktop.
Save CatChenal/39190d080f3aed62c3a559119c24ab4a to your computer and use it in GitHub Desktop.
Some flavors of `ipywidgets.interact[]` require a print statement in the dependent function

Example 1 - Simplest implementation: using interact:

=> No need for the function to have a print/display statement => This should also be the behavior of interactive & interactive_output, but it's not

import ipywidgets as ipw


@ipw.interact(x=(20.,250.,5),
          a=(-60.,60.,10),
          b=(-6_000.,6_000,100))
def linear_model(x: float, a: float, b: float) -> float:
    """Linear model of the form y = a * x + b""" 
    return a * x + b
    
# OR:
# using the non-decorator version keeps the function 
# intact for non-interactive use: 
ipw.interact(linear_model, 
             x=(20.,250.,5),
             a=(-60.,60.,10),
             b=(-6_000.,6_000,100)
            )

Example 2 - Using interactive:

=> the function needs a print/display statement => linear_model_ui has the modification

def linear_model_ui(x: float, a: float, b: float) -> float:
    """Linear model of the form y = a * x + b"""
    out = a * x + b
    display(out)
    return out

ipw.interactive(linear_model_ui,
                x=(20.,250.,5),
                a=(-60.,60.,10),
                b=(-6_000.,6_000,100)
               )

Example 3 - Using interactive_output => more UI control:

=> the function needs a print/display statement

descs = ['x: x var', 'a: x coeff', 'b: y intercept']

x = ipw.FloatSlider(min=20., max=250., step=5, value=45.)
a = ipw.FloatSlider(min=-60., max=60., step=10, value=30.)
b = ipw.FloatSlider(min=-6_000., max=6_000, step=100, value=1_000.)
param_controls = ipw.VBox([ipw.HBox([ipw.Label(descs[0]),x]),
                           ipw.HBox([ipw.Label(descs[1]),a]),
                           ipw.HBox([ipw.Label(descs[2]),b])
                          ])

#result = ipw.interactive_output(linear_model_ui, {'x': x, 'a': a, 'b': b})
#gui = ipw.HBox([param_controls, ipw.Label("Result: "), result])
# OR:
gui = ipw.HBox([param_controls,
                ipw.Label("Result: "),
                ipw.interactive_output(linear_model_ui, {'x': x, 'a': a, 'b': b})
               ])

display(gui)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment