Search code examples
python-3.xwidgetdefault-valueinteractiveipywidgets

How to tell `ipywidgets.interactive`, that it should consider only specific parameters as widgets?


It seems like ipywidgets.interactive tries to make every imput after the function to be a widget. In the following example, I get two widgets, one for age and one for name:

import ipywidgets 

def greetings(age, name='John'):
    print(f'{name} is {age} years old')

ipywidgets.interactive(greetings, age = widgets.IntSlider(), name = "Bob")

My expectation was, that I only get one widget for age, since it is of type ipywidgets.widgets.widget_int.IntSlider whereas "Bob" is of type str (where I don't see the link to widgets). The automated widget creation causes two problems: 1. I don't want that the user can specify every parameter 2. Some parameters like tuples (not shown in the example) will result in an error.

How to tell ipywidgets.interactive, that it should consider only specific parameters as widgets?

help(ipywidgets.interactive) and the documentation were not helpful.


Solution

  • Firstly, thanks for the clear example and description.

    You can leverage the fixed function in ipywidgets to pass fixed kwargs of any type through your interactive call, but without generating widgets for them. See below:

    import ipywidgets 
    
    def greetings(age, name='John'):
        print(f'{name} is {age} years old')
    
    ipywidgets.interactive(greetings, 
                           age = ipywidgets.IntSlider(), 
                           name = ipywidgets.fixed("Bob")
                          )
    

    You should also be able to pass tuples through this method. See more information in the documentation: https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html#Fixing-arguments-using-fixed