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:

import external_file

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

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:

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

if __name__ == "__main__":

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

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

    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