I have general questions about how callbacks work. As per examples on Plotly website, a common convention (or maybe correct way) of writing callbacks looks like this:
@app.callback(
Output('graph-with-slider', 'figure'),
Input('year-slider', 'value'))
def update_figure(selected_year):
filtered_df = df[df.year == selected_year]
fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",
size="pop", color="continent", hover_name="country",
log_x=True, size_max=55)
fig.update_layout(transition_duration=500)
return fig
My questions are:
-
Do I have to always define functions below callbacks? Does it matter where I place my code associated with callback?
-
Can I save functions in another file and import them in app.py file under callback?
For example, can the code above be written like this:
import functions
@app.callback(
Output('graph-with-slider', 'figure'),
Input('year-slider', 'value'))
functions.function1(selected_year)
- Is it possible to define a function with *args or **kwargs? I’m asking this because, when I define a function explicitly with arguments, callback expects that those arguments are not empty from the beginning. I know, that I can avoid it by adding a control like this
if argument is not None:
, but it is not convenient.