UnboundLocalError: local variable 'fig' referenced before assignment

I am getting the above error while plotting the bar graphs and appending them to results. Is there any solution.

import dash
import pandas as pd
import plotly.express as px
from dash import Dash, html, dcc, Output, Input, MATCH
import dash_bootstrap_components as dbc

app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

df = pd.read_csv('assets/nights.csv')

ls1=df['City'].unique
app.layout = dbc.Container([

dcc.Dropdown(id='my-var', multi=True, persistence = True,
           persistence_type = 'memory',
                         options=[{'label':x, 'value':x}
                                  for x in ls1]),

html.Div('container','children')
)]

@app.callback(
    Output('container', 'children'),
   [Input("my-var", "value")]
   
)
def update_graphs(val):
  d1=df.loc[df.City==var]
  fig = px.bar(d1, x="City", y="Cost", barmode="group",)
  output.append(dcc.Graph(id={'type': 'dynamic-graph','index': val },figure=fig))
  output.append( html.Div(id={'type': 'container', 'index':val}))
  return output

UnboundLocalError: local variable ‘fig’ referenced before assignment

Traceback (most recent call last):
File “C:\Users\Local\Temp\ipykernel_20424\180331076.py”, line 16, in update_graphs

File “C:\Users\Lib\site-packages\plotly\express_chart_types.py”, line 368, in bar
return make_figure(
File “C:\Users\Lib\site-packages\plotly\express_core.py”, line 2182, in make_figure
fig = init_figure(
File “C:\Users\Lib\site-packages\plotly\express_core.py”, line 2327, in init_figure
for annot in fig.layout.annotations:
UnboundLocalError: local variable ‘fig’ referenced before assignment

This line:

fig =px.bar(x='country',y='population')

I assume x and y are columns of a DataFrame, but you never specify the DataFrame to use.

could also be a scope issue when fig=px.bar() was declared in a different function or not in the function where result.append() was declared.

@dashapp, is result.append() right below fig = px.bar()?

@adamschroeder I updated it as a new topic

hi @dashapp
I don’t think this is a solution yet, but heads up that you have a spelling mistake with ‘var’. You probably meant val.

What is “output.append”? What is output coming from?

@adamschroeder Sorry that was a typo. so when I click a value from the dropdown output should return a bar plot and empty container. Suppose I select two columns output should be two bar graphs and empty container which can take hoverdata and click data. My code is working properly and only error is with fig. Even if I remove fig variable and add the graph in figure variable in dcc.graph, the error persists. It has something to do with plotly. Can you check this.

An UnboundLocalError is raised when a local variable is referenced before it has been assigned. In most cases this will occur when trying to modify a local variable before it is actually assigned within the local scope. Python doesn’t have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they’re declared global with the global keyword). A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can’t modify the binding in the enclosing environment. UnboundLocalError happend because when python sees an assignment inside a function then it considers that variable as local variable and will not fetch its value from enclosing or global scope when we execute the function. However, to modify a global variable inside a function, you must use the global keyword.

In my case the error is
UnboundLocalError: local variable ‘fig’ referenced before assignment

Traceback (most recent call last):
File “C:\Users\Local\Temp\ipykernel_20424\180331076.py”, line 16, in update_graphs

File “C:\Users\Lib\site-packages\plotly\express_chart_types.py”, line 368, in bar
return make_figure(
File “C:\Users\Lib\site-packages\plotly\express_core.py”, line 2182, in make_figure
fig = init_figure(
File “C:\Users\Lib\site-packages\plotly\express_core.py”, line 2327, in init_figure
for annot in fig.layout.annotations:

I haven’t used fig variable at all. Its just related to plotly fig.

I get the error too. But I found my d1 is empty dataframe. when I fix the filt operation, it works