Python JupyterDash unable to access callback modified objects
Solution 1:
From what I can tell, the jupyterdash extension is just spawning a server from within jupyter. So I believe you're running up against how dash handles server state, similar to a plain old dash app. So you're essentially trying to access an updated component value outside of the server context, which is not possible (see answer here). Even though you're running from jupyter, It's still a self contained server that the client (which is you in the next jupyter cell) cannot access dynamically and so as you have it, your get_data_frame
will only ever be able to access the df
you instantiated with.
To get around this, you need to store your updated dataframe in some persistent form available outside of the app. How you do that depends on your use-case but basically every time your on_col_selection
is triggered, you need to write your dataframe to something outside of the app. For example, the following will reproduce the behavior you're looking for:
def callbacks(self, app):
"""Initialize app callbacks"""
@app.callback(
Output("data-store", "data"),
Input("cols", "value"),
State("data-store", "data"),
prevent_initial_call=True,
)
def on_col_selection(col_name, df_jsonified):
df = (pd.read_json(df_jsonified, orient="split")
.drop(col_name, axis=1)
)
df.to_csv("/path/to/some_hidden_file_somewhere.csv", index=False)
return df.to_json(date_format="iso", orient="split")
@property
def get_data_frame(self):
"""property to retrieve dataframe from data-store"""
return pd.read_csv("/path/to/some_hidden_file_somewhere.csv")
If you're going to be sharing your code with others, you probably want something more sophisticated to keep track of user-dependent files. For example, an on-disk flask cache could work well here. Also check out Examples 3 and 4 on dash's Sharing Data Between Callbacks page.
Depending on what your design plans are, you might also want to look into dash's DataTable for displaying and interacting with the dataframe from within the dash app.