Don't understand callback context documentation

there is a global variable dash.callback_context , available only inside a callback
from Advanced Callbacks | Dash for Python Documentation | Plotly

how is it a global variable if it’s only available inside a callback?

Please advise if the heading is relevant

Hi,

Please refer to the following link (on top) which has some context and examples of usage

2 Likes

Regarding it being a global variable, this might well be the case, but I assume that it will only be set
and have a valid state when entering a callback

Codewise, if you look into Dash source code, it is enforced that dash.callback_context can only be used inside a callback. Check the has_context decorator.

The biggest magic behind the callback context happens in context_value variable. I didn’t dive in the source code behind that object, but this is how the proper context is derived.

What I can see is that calling dash.callback_context outside of a callback might have worked perfectly fine, if Dash would have allowed you to do that. However, Dash will raise an exceptions.MissingCallbackContextException error that explicitly prevents you from doing this.

I don’t know the magic to how the context is set, but if you want to understand better, my suggestion is to start looking at the contextvars library.

2 Likes