Dash callback in a separate file

You can use a function pattern instead of import the app from a global in a file. Importing from global leads to circular imports issues depending on the on the os. Dash-docs got this problem, on windows it won’t register the examples callbacks unless you change the imports.

Basically, instead of importing the app you take it as a parameter where you need it. In your main app file you import the function and call it with your app. This way you don’t import the app in multiple files.

my_app/layout.py

import dash_html_components as html

layout = html.Div([
    html.Button('Click me', id='btn'),
    html.Div(id='output')
])

my_app/callbacks.py

from dash.dependencies import Output, Input

def register_callbacks(app):

    @app.callback(Output('output', 'children'), [Input('btn', 'n_clicks')])
    def on_click(n_clicks):
        return 'Clicked {} times'.format(n_clicks)

app.py

import dash
from my_app.layout import layout
from my_app.callbacks import register_callbacks

app = dash.Dash
app.layout = layout
register_callbacks(app)
18 Likes