0

From this example

@app.callback(
    dash.dependencies.Output('output-container-button', 'children'),
    [dash.dependencies.Input('button', 'n_clicks')],
    [dash.dependencies.State('input-box', 'value')])
def update_output(n_clicks, value):
    return 'The input value was "{}" and the button has been clicked {} times'.format(
        value,
        n_clicks
    )

I have discovered this is called a "decorator" and according to this answer the most common ones are @property, @classmethod, and @staticmethod.

This example is none of those. app is an object which already exists. So, syntactically speaking (I'm looking for a Python answer, not a Dash answer), what does @object.method do?

spraff
  • 32,570
  • 22
  • 121
  • 229
  • 4
    The exact same thing as any other decorator? You can also have `@one.two.three.whatever` as well, it doesn't change too much. – ForceBru Aug 27 '19 at 09:43
  • 1
    A [decorator](https://docs.python.org/3/glossary.html#term-decorator) is just a function (or callable) that returns another function. It makes no difference how or where such a function is defined. – ekhumoro Aug 27 '19 at 10:05

1 Answers1

1

This is a decorator as well, a decorator is applied on a function and can take additional arguments.

If you have a function

def multiply_all_args(f, x):
  def new_f(*args, **kwargs):
    return f(*[x*a for a in args], **{k: x*v for k, v in kwargs})
  return new_f

Then doing

@multiply_all_args(x=42)
def g(x=1):
  print(x)

is the same as doing
def g(x=1):
  print(x)
g = multiply_all_args(g, x=42)

In your situation this is exactly what happens, so your code is equivalent to

def update_output(n_clicks, value):
    return 'The input value was "{}" and the button has been clicked {} times'.format(
        value,
        n_clicks
    )
update_output = app.callback(update_output,
    dash.dependencies.Output('output-container-button', 'children'),
    [dash.dependencies.Input('button', 'n_clicks')],
    [dash.dependencies.State('input-box', 'value')])
Statistic Dean
  • 4,861
  • 7
  • 22
  • 46