App.callback without @

In Python, the following

@decorator
def function(*args, **kwargs):
    ...

is syntactic sugar for

def function(*args, **kwargs):
    ...

function = decorator(function)

i.e. decorators are higher order functions that (usually) modify the functionality of a function without you having to explicitly rewrite it.

app.callback is no different, so

@app.callback(Output(...), [Input(...)])
def my_callback(...):
    ...

is the same as

def my_callback(...):
    ...

my_callback = app.callback(Output(...), [Input(...)])(my_callback)

However, app.callback doesn’t actually modify the functionality of the function it’s decorating, instead it registers the function in a callback map that dash uses internally to keep track of what needs to be updated and how it should be updated. Hence you don’t actually need to do anything with the return value, it’s fine to just do

def my_callback(...):
    ...

app.callback(Output(...), [Input(...)])(my_callback)

I’d say the decorator syntax is cleaner, however the latter approach can be useful when you have several callbacks to define with the same logic, then you only have to write the logic once. Something like

def my_callback(...):
    ...


for i, o in zip(inputs, outputs):
    app.callback(Output(o, "children"), [Input(i, "n_clicks")])(my_callback)
5 Likes