Define app.callback in a separate file

My app is defined with a layout, followed by an @app.callback(), and then a function, as is standard practice. Is it possible, however, to define the callback statement and the function in a separate file?

I would like to be able to have my script read something like this:

my_app.py

import external_file

app.layout = [LAYOUT HERE]
@app.callback(external_file().callback)
def do_stuff():
  ...

external_file.py

class callback():
  def __init__(self):
    callback = Output(), [Input()])

I didn’t show it above for brevity, but it would be ideal to have the function definition following the app.callback in the external file as well.

Sure, you can do that. Here’s an example:

main.py

from dash import Dash, html, dcc, callback
from external_file import PongCallback

app = Dash(__name__)

app.layout = html.Div([
    dcc.Interval(id='interval', interval=1000),
    html.Div('PING', id='main-div')
])

# Pong callback
callback(*PongCallback.callback_params)(PongCallback())

if __name__ == "__main__":
    app.run(debug=True)


external_file.py

from dash import Input, Output
from dash.exceptions import PreventUpdate


class PongCallback:
    callback_params = (
        [Output('main-div', 'children')],
        [Input('interval', 'n_intervals')]
    )

    @staticmethod
    def callback(n_intervals):
        if n_intervals is None:
            raise PreventUpdate

        if n_intervals % 2 == 0:
            return ['PONG']
        return ['PING']

    def __call__(self, *args):
        return self.callback(*args)

1 Like