0

I have a fairly easy Python3 script, which also uses Dash:

app = dash.Dash(__name__)
app.layout = html.Div(id='mydiv', ...)

fff = False

@app.callback(
    Output('mydiv', '...'),
    Input('mydiv', 'myevent')
def update(evt):
    print(fff)
    return dash.no_update

This correctly prints 'False' when the update function is called on click on the div.

However, a slight modification makes python not interpret my whole file:

app = dash.Dash(__name__)
app.layout = html.Div(id='mydiv', ...)

fff = False

@app.callback(
    Output('mydiv', '...'),
    Input('mydiv', 'myevent')
def update(evt):
    *** print(fff)
    fff = True
    return dash.no_update

This makes "Unresolved reference 'fff'" in line marked with ***

If I put "nonlocal fff" in front of that unresolved reference line, there is a syntax error of

SyntaxError: no binding for nonlocal 'fff' found

Why is this happening? Why can the python print fff's value if I don't want to modify it?

And how can I modify it in this update function?

Daniel
  • 2,318
  • 2
  • 22
  • 53
  • 1
    You've defined a local variable which shadows the *global* name `fff`. It doesn't matter where in the scope the assignment occurs; just the *presence* of the assignment makes the code generator mark the name as local (even if the assignment is never executed at runtime). – chepner Dec 05 '21 at 16:23
  • An assignment to a variable in a function (anywhere in that function) will cause the compiler to mark the variable as local. If you want to assign to a global variable in your function then you can use the `global` statement, although mutating global state is generally an antipattern – juanpa.arrivillaga Dec 05 '21 at 17:31
  • You also appear to be missing the closing parenthesis for `@app.callback`. – Karl Knechtel Dec 05 '21 at 17:38

0 Answers0