leveredkiddo
leveredkiddo

Reputation: 11

Defining a global variable from an ipywidget function using JupyterNotebook

I'm using ipywidgets to allow users to choose some value and I want to assign the result of the function inside the widget to a variable outside of the function and use it on the next cell of the Notebook (I tried using a global variable but I couldn't make it work):

def issuer_choice():

    from ipywidgets import widgets
    from IPython.display import display, clear_output
    import pandas as pd

    def myfunc(idnum):
        return data.loc[idnum]['cod']

    def on_button_clicked(b):
        global ticker
        ticker = myfunc(w.value)
        with output:
            clear_output()
            print('Ticker CIQ: ' + ticker)

    data = pd.read_csv('data.csv', sep=',', index_col = 1)
    w = widgets.Dropdown(options=list(data.index), description = 'Label:')

    button = widgets.Button(description="Obtain ID")
    output = widgets.Output()

    display(w)        
    display(button, output)
    button.on_click(on_button_clicked)
    return ticker

When calling this function as result = issuer_choice() and clicking on the button, the code manages to print ticker correctly each time, meaning the value inside the function is updated when choosing among the options. However, calling print(result) on the next cell prints None, meaning ticker is not getting assigned to result?

*data.csv is just a one column DataFrame where a list of ID's and names are stored.

I'm thinking it has to be about the scope of the ticker variable, but I have no clue. I would appreciate any help.

Upvotes: 1

Views: 3786

Answers (1)

ac24
ac24

Reputation: 5575

If you're asking for global ticker then make sure ticker is already a defined name in your global scope, even if you set it to None, then you can call it later in your global scope.

Also, if you replace things like read_csv calls with a simple fake dataframe that gives the same behaviour, it makes it much easier to pick up and work with your example.

ticker = None

def issuer_choice():

    from ipywidgets import widgets
    from IPython.display import display, clear_output
    import pandas as pd

    def myfunc(idnum):
        return data.loc[idnum]['cod']

    def on_button_clicked(b):
        global ticker
        ticker = myfunc(w.value)
        with output:
            clear_output()
            print('Ticker CIQ: ' + str(ticker))

    data = pd.Series({'A':1, 'B': 2, 'C': 3})
    data = data.to_frame(name='cod')
    w = widgets.Dropdown(options=list(data.index), description = 'Label:')

    button = widgets.Button(description="Obtain ID")
    output = widgets.Output()

    display(w)        
    display(button, output)
    button.on_click(on_button_clicked)

Upvotes: 1

Related Questions