Search code examples
pythonpython-3.xcallbackplotly-dashplotly-python

Dash CallBacks A way to get a list of the Outputs Id or a static variable for the function


so the problem is this: I am creating a generic Callback that goes as follows:

# create the callback for the page path
    x = [Output(f"sideMenuSection{Section.buttonCount}Title", "style"), [Output(f"page-{name}-link", "active") for name in pages]]
    outputList = [*chain(*(e if isinstance(e, list) else [e] for e in x))]
    # Path Callback
    app.callback(
        outputList,
        [
            Input("url", "pathname"),
            Input(f"sideMenuSection{Section.buttonCount}Title", "style")
        ],
    )(toggle_active_links1)

The Function toggle_active_links1 is in the following code:

def toggle_active_links1(pathname, style, names):
    print(names)
    pathList = [pathname == name for name in names]
    if True in pathList:
        return pathList.insert(0,style)
    else:
        return pathList.insert(0,style)

I do not have an input for names! that is because I have no way of getting dynamically the names from any input in my app, now the names are in the list of outputs I have in the callback.

I see 2 options that I have no idea how to do both of them and am not sure if they're possible:

  1. Somehow get a list of the Outputs inside the function and from here it's easy to find the list of names I need.

  2. create a static variable somewhere in the file for each object I create maybe even creating a class for each toggle_active_links1 I create and try that. it just sounds so inefficient and also I have no idea if that's possible or would work.

What do you guys think? How can I go on from here?


Solution

  • I will try to address your first proposed option in this answer:

    Somehow get a list of the Outputs inside the function and from here it's easy to find the list of names I need.

    You can get a list of outputs inside a callback through dash.callback_context:

    outputs_list, inputs_list, and states_list: lists of inputs, outputs, and state items arranged as you'll find them in the callback arguments and return value.

    https://dash.plotly.com/advanced-callbacks

    So you could use dash.callback_context.outputs_list inside your callback function and go from there.