On_session_destroyed() cannot access module level imports / variables

Hi,

It seems that on_session_destroyed() is run in some isolated context such that it has no access to module level variables (e.g., logger) and imports

E.g., for the following sample on_session_destroyed callback, it has no access to np.

import numpy as np

def my_on_session_destroyed(session_context):
    print("my_on_session_destroyed():", np.nan)

Bokeh server outputs the following error:

DocumentLifeCycleHandler on_session_destroyed callback 
<function my_on_session_destroyed at 0x714ea77614e0> 
failed with following error: name 'np' is not defined

Is that the expected behavior? I’m running it with bokeh 3.7.3 and tornado 6.5.1

Thanks.

Sam

Complete test codes:

from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.plotting import figure, ColumnDataSource

import numpy as np


def my_on_session_destroyed(session_context):
    # # Uncomment the following line to make the codes to work
    # #  (the module level import seems to have no effect here)
    # import numpy as np
    print("my_on_session_destroyed():", np.nan)


def create_interact_ui(doc):
    fig = figure(
        title="Test Bokeh server",
    )

    source = ColumnDataSource(data=dict(
        x=np.array([0, 5, 10], dtype=float),
        y=np.array([4, 6, 8], dtype=float),
        ))
    fig.scatter(source=source, size=16, marker="square", fill_color="red")

    doc.add_root(layout([
        [fig, ]
    ]))
    doc.on_session_destroyed(my_on_session_destroyed)


#
# Main
#
create_interact_ui(curdoc())

Not expected, please feel free to submit a GitHub Issue with full details.

I did verify that using a separate app_hooks.py module with a “directory style” app does work as expected, so that is my immediate suggestion to you.

Thanks for looking into it. Could you elaborate on what you mean by app_hooks.py module? Because my actual problem is in a “directory style” app. Even with the above test codes, if I save it as some_dir/main.py and serve it with bokeh serve some_dir/, the problem still exists.

Described here:

https://docs.bokeh.org/en/latest/docs/user_guide/server/app.html#lifecycle-hooks

1 Like

Thanks for the pointers to the documentation of app_hooks.py.
The issue is filed at callback added by `doc.on_session_destroyed()` cannot access module level imports / variables · Issue #14538 · bokeh/bokeh · GitHub .

1 Like