Black Lives Matter. Please consider donating to Black Girls Code today.

App.callback without @

Hello

Apologies for the newbie questions but i have seen in some examples that sometimes we have
@app.callback
and other times just
app.callback

I would always expect there to be an ‘@’

Could anybody please explain when i would just have app.callback?

Many thanks.

1 Like

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)
4 Likes

You can get a better understanding of Dash callback functions and decorator functions using below url:

1 Like

Very informative…thank you!

1 Like