[Python] Python Decorator as Callback in Dash Using Dash Object That is an Instance Variable -...

Discussão em 'Python' iniciado por Stack, Janeiro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm updating some code to use Dash and plotly. The main code for graphing is defined within a class. I replaced some Bokeh widgets with Dash controls, and ended up with a callback that looks like this:

    class MakeStuff:
    def __init__(self, ..., **optional):
    ...
    self.app = dash.Dash(...)
    ...

    @self.app.callback(
    dash.dependencies.Output('indicator-graphic', 'figure'),
    [dash.dependencies.Input('start-time-slider', 'value'),
    dash.dependencies.Input('graph-width-slider', 'value')]
    )
    def update_graphs(self,range_start,graph_width):
    print(...)


    I am following some examples from the Dash website. I was able to run the examples, including callbacks. In my code, without the decorator, the code runs without error, producing the graphics and controls as I expected it to. (Of course, the code is incomplete, but there is no error.) When I include the decorator, I get this error:


    NameError: name 'self' is not defined
    ​

    I tired it this way, first, just mimicking the code examples:

    class MakeStuff:
    def __init__(self, ..., **optional):
    ...
    app = dash.Dash(...)
    ...

    @app.callback(
    dash.dependencies.Output('indicator-graphic', 'figure'),
    [dash.dependencies.Input('start-time-slider', 'value'),
    dash.dependencies.Input('graph-width-slider', 'value')]
    )
    def update_graphs(self,range_start,graph_width):
    print(...)


    Of course, the variable "app" is only know within the scope of the init function, so it's no surprise that that doesn't work, giving the similar error:


    NameError: name 'app' is not defined
    ​

    Is there a straightforward way to set up this decorator to work while still keeping my code within a class definition? I am guessing some pre-processing is going on with the decorator, but I don't understand it well enough to come up with a solution.

    Continue reading...

Compartilhe esta Página