spraff
spraff

Reputation: 33445

What does @object.method do in Python?

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?

Upvotes: 0

Views: 85

Answers (1)

Statistic Dean
Statistic Dean

Reputation: 5290

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')])

Upvotes: 1

Related Questions