Examples of good programming style/use of classes in bokeh

Hi All,

Browsing through the various bokeh examples in the gallery and showcase, it seems that a typical bokeh app is written with the main figures, glyphs, data sources, and so on as global variables in the main script and whatever manipulations are done (callbacks, etc) are functions in the main script with global scope.

I’m interested in people’s view of what “good python style” is for a bokeh app that runs under the server. For example, do people put the elements of the plot in a class? How do you handle streaming data in that situation? What do you use to instantiate the plot?

Any pointers to examples would be welcome.


This is something (usage of classes in bokeh plots) I’ve started practicing recently. Although I can’t share the entire code at this point, my structure is similar as below.

class plot_attributes(object):
    def plot_format(self, plot):

        format plot like background_fill_color, border_fill_color..
        Instead of repeating it in multiple places.


        return plot

class plots(plot_attributes):
        def exploration_plots(self):

        """ Create all the necessary plots"""

        # To format plots
        self.fig_name = self.plot_format(self.fig_name)
        # I return a panel object here but it could be anything like a figure.

        return panel_1

class main(plots):
        def __init__(self):
              Define all variables that are used across multiple classes, so that you don't have 
              to do it in every other class.


        def run_classes(self):
              tab_1 = self.exploration_plots() # function from class plots to create panel_1

        tabs = Tabs(tabs=[tab_1], tabs_location='above')

        return tabs

tabs = main().run_classes()

curdoc().title = "Bokeh Server App"

In my case, this has reduced the size of code and made the process easier for keeping track of variables.

For example, in my case there are 6 tabs and each tab would have least 3-4 plots, 4-5 widgets and 2-3 data sources, all interacting between them and with other libraries like sklearn and scipy. Compared to the first version (keeping all variables in global scope) of code, this method is better in my case.


@jeremy9959 The examples are all simple scripts in order that some particular Bokeh feature can be demonstrated in isolation without a lot of unrelated distraction. Also, this style of usage is common in notebooks or other exploratory settings. For “real applications” it’s definitely warranted to apply more structure and design, but I’m not sure I have any Bokeh-specific advice to render. All the standard guidance about separating concerns, avoiding global state, and factoring in to easily testable components, etc. applies as it would in any situation without Bokeh.