Learn how to use Dash Bio for next-gen sequencing & quality control. 🧬 Register for the Oct 27 webinar.

Dash Callback inside a Function

Hello. I would like to use @app.callback in a function that is in another file than the main dashboard file. This function is called in main dashboard file and returns html.Div(), and I would like to use callback for a property within that Div. The code looks like below:


from function_process import function_process

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)

app.layout = function_process()


def function_process():

return html.Div(children=[
      dcc.Tabs(id='selected_tab', children=[

I would like to write a callback within function_process.py to return specific content to ‘content_tab_selected’ based on the tab choice in ‘selected_tab’. Where should I place the @app.callback for this purpose?

Technically, it doesn’t really matter at all where you put your @app.callbacks. In practice, I would put them where it makes logically sense, probably in the same file or folder as the element that may trigger the callback.

If you want to put the callbacks into separate files, make sure that creating the app instance and starting the server are in separate files (to prevent circular dependencies). For example

# app.py
app = dash.Dash(__name__)
# index.py

Using the filenames as above, you would import app from app in the files that define the callbacks, and then, instead of running

python app.py

to start the server, you would run

python index.py

to start it.

1 Like

Oops, I think I misread the question somehow. Callbacks in dash are little bit special. They are not regular python functions, but instead (I assume) @app.callback is syntactic sugar to make dash to create Javascript code out of your python code. This is the reason why All Callbacks must be defined before server starts.

To define a callback that returns something into content_tab_selected when you change value property of the dcc.Tabs selected_tab, you would use something like

    Output('content_tab_selected', 'children'),
    [Input('selected_tab', 'value')]
def this_name_can_be_anything_descriptive():
    return html.Div('abc')
1 Like