Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have an argument possible values dependent on another argument with IPython Widgets?

Assume I have this simple function in Python:

def f(gender, name):
    if gender == 'male':
        return ranking_male(name)
    else:
        return ranking_female(name)

where gender belongs to ['male', 'female'] whereas name belongs to ['Adam', 'John', 'Max', 'Frodo'] (if gender is male) or ['Mary', 'Sarah', 'Arwen'] (otherwise).

I wish to apply interact from ipywidgets to this function f. Normally one would do

from ipywidgets import interact
interact(f, gender = ('male', 'female'), name = ('Adam', 'John', 'Max', 'Frodo'))

The problem is that the admissible values for name now depend on the value chosen for gender.

I tried to find it in the docs but couldn't find it. The only thing I think may be important is This is used to setup dynamic notifications of trait changes.

    Parameters
    ----------
    handler : callable
        A callable that is called when a trait changes. Its
        signature should be ``handler(change)``, where ``change```is a
        dictionary. The change dictionary at least holds a 'type' key.
        * ``type``: the type of notification.
        Other keys may be passed depending on the value of 'type'. In the
        case where type is 'change', we also have the following keys:
        * ``owner`` : the HasTraits instance
        * ``old`` : the old value of the modified trait attribute
        * ``new`` : the new value of the modified trait attribute
        * ``name`` : the name of the modified trait attribute.
    names : list, str, All
        If names is All, the handler will apply to all traits.  If a list
        of str, handler will apply to all names in the list.  If a
        str, the handler will apply just to that name.
    type : str, All (default: 'change')
        The type of notification to filter by. If equal to All, then all
        notifications are passed to the observe handler.

But I have no idea how to do it nor to interpret what the doc string is talking about. Any help is much appreciated!

like image 243
gota Avatar asked Oct 19 '22 06:10

gota


1 Answers

For example you have brand and model of car and model depends on brand.

d = {'Volkswagen' : ['Tiguan', 'Passat', 'Polo', 'Touareg', 'Jetta'], 'Chevrolet' : ['TAHOE', 'CAMARO'] }

brand_widget = Dropdown( options=list(d.keys()),
                         value='Volkswagen',
                         description='Brand:',
                         style=style
                       )
model_widget = Dropdown( options=d['Volkswagen'],
                         value=None,
                         description='Model:',
                         style=style
                       )

def on_update_brand_widget(*args):
    model_widget.options = d[brand_widget.value]

brand_widget.observe(on_update_brand_widget, 'value')
like image 113
mrgloom Avatar answered Jan 04 '23 07:01

mrgloom