def power_func(k):
def power(x):
return x**k
return powerLecture 22
Shiny is also available as a Python package, shiny. It is a separate implementation written in Python, not a wrapper around the R package.
Almost everything from the last two lectures carries over.
The same split between a UI and a server function
The same reactive model with inputs, outputs, reactive expressions, and observers
The same browser-side code, so apps look and behave the same
The bslib components (cards, value boxes, sidebars, layouts) are built in
What changes is the syntax, and most of today is about mapping what we already know from R onto Python.
Add the package to a project with uv,
The app is written as a python script and then run from the command line via:
The --reload flag watches app.py and restarts the app every time the file is saved.
Positron and VS Code have a Shiny extension that adds a run button and shows the app in a viewer pane, much like RStudio does for R.
Shiny for Python has two syntaxes for writing an app.
Shiny Express mixes UI and server code together in one script. It is compact and reads like a notebook, which makes it nice for small apps. (Competes with streamlit)
Shiny Core keeps a UI object and a server function separate, just like R.
We will use Core throughout. It maps directly onto the R apps we have written, and what you learn transfers to Express easily.
A function can be defined inside another function. The inner function can use the variables of the outer one, including its arguments.
A Shiny server function works the same way. Every output and reactive is a function defined inside server(), which is how they can all see input.
A decorator is a function that takes a function and returns something to use in its place, usually another function.
Here render() stores each function by name in a dictionary and returns it unchanged.
We can then access those functions from the outputs dictionary,
This is roughly what Shiny does. The name of a decorated function is the id of the output it fills.
A decorator can take arguments. repeat(2) is called first and returns the decorator to apply.
Stacked decorators are applied from the bottom up, so the order matters.
In a Python call all positional arguments must come before any keyword arguments.
In shiny the UI functions take their children as positional arguments, so the named options that R code often puts first have to move to the end.
ui holds the UI functions and App ties the pieces together.
render for the output renderers andreactive for the reactive tools.app_ui by convention, since the name ui is taken by the module.shiny run app.py looks for an object named app by default. Another name can be given as shiny run app.py:my_app.Every UI function lives in ui and uses snake_case. Inputs start with input_ and outputs start with output_.
| R | Python |
|---|---|
sliderInput() |
ui.input_slider() |
numericInput() |
ui.input_numeric() |
selectInput() |
ui.input_select() |
actionButton() |
ui.input_action_button() |
plotOutput() |
ui.output_plot() |
textOutput() |
ui.output_text() |
uiOutput() |
ui.output_ui() |
h4(), p(), div() |
ui.h4(), ui.p(), ui.div() |
page_sidebar(), sidebar() |
ui.page_sidebar(), ui.sidebar() |
card(), value_box() |
ui.card(), ui.value_box() |
The bslib functions keep their names, since they were already in snake_case with consistent prefixes.
title moves to the end.class is reserved in Python, so the argument is class_.In R an input is read as input$x. In Python it is input.x(), with parentheses.
Python is being more explicit here. Every reactive value is an object, and calling it both returns the current value and records the dependency. This is the same convention R already uses for reactive expressions.
Outputs are where the decorators from earlier come in. Each output is a decorated function defined inside server().
render*() function wrapped around a block of code becomes a @render decorator on a function with no arguments.output. The function name is the output id, so summary_title() fills ui.output_text("summary_title").return (a Python function without a return returns None).@render.plot works with matplotlib and anything built on it, such as seaborn and plotnine. Return the figure or axes, or draw with pyplot and return nothing.
For tables use @render.data_frame with ui.output_data_frame(), which shows a pandas or polars data frame as a sortable grid.
reactive() becomes the @reactive.calc decorator. The result is used in the same way in both languages, by calling d() from another reactive context.
Nothing about the behavior changes. A calc is lazy, it caches its value, and it is invalidated when any input it read changes.
observe() becomes @reactive.effect. The name reflects what an observer is for, which is running code for its side effects.
_. Reusing _ for different effects is fine. reactive.calcs and renders need unique names.update*() functions are in ui as ui.update_slider(), ui.update_numeric(), and so on. They find the current session on their own, so session is not passed.bindEvent() becomes the @reactive.event() decorator, which takes the reactive value(s) to listen to.
input.run without parentheses. We are handing over the reactive object to watch, not reading its current value.@reactive.event(input.run, input.reset), just like bindEvent.@reactive.event() goes directly above the def, underneath @reactive.calc, @reactive.effect, or @render.*. Decorators apply from the bottom up, so the event wraps the function first. The wrong order is an error.ignoreNULL and ignoreInit become ignore_none and ignore_init.renderUI() becomes @render.ui, paired with ui.output_ui(). A list comprehension takes the place of map(), and * the place of !!!.
req() works the same way in both languages: if any argument is missing, the calculation stops quietly and the output stays blank.
req() is imported from shiny alongside App, reactive, render, and ui. It receives values, so the inputs are called, input.file().None, False, "", and empty lists, but also 0, which R treats as a valid value. A data frame cannot be passed to req() at all, since pandas raises an error when asked whether one is true.There is no validate() or need(). Instead, raise a SafeException and its message is shown in place of the output.
SafeException’s message is always shown.@reactive.calc, it reaches every output that uses the calc, just like validate().validate() gives.A few more tools have direct equivalents in Python.
| R | Python |
|---|---|
reactiveVal(0) |
reactive.value(0) |
isolate(input$x) |
with reactive.isolate(): |
invalidateLater(1000) |
reactive.invalidate_later(1) |
downloadHandler() |
@render.download |
tags$small() |
ui.tags.small() |
HTML(), markdown() |
ui.HTML(), ui.markdown() |
Writing input.x instead of input.x() when reading a value, or input.run() instead of input.run inside @reactive.event().
Forgetting to return the value from a calc or an output.
An output function whose name does not match its id in the UI. Nothing fails and the output just stays empty.
Two calcs or outputs with the same name. The second definition silently replaces the first.
Putting @reactive.event() above @reactive.calc or @render.* instead of below it.
Keyword arguments ahead of the children in a UI function, which is a syntax error.
A missing comma between UI components. The error message often points at the wrong line.
Our goal is the app from last lecture, without the pieces that depended on bs_theme().
The statistical pieces change along with the Shiny ones.
| R | Python |
|---|---|
seq(0, 1, length.out = 1001) |
np.linspace(0, 1, 1001) |
dbeta(p, a, b) |
stats.beta.pdf(p, a, b) |
dbinom(x, n, p) |
stats.binom.pmf(x, n, p) |
tibble() |
pd.DataFrame() |
pivot_longer() |
.melt() |
summarize(..., .by = distribution) |
.groupby("distribution").agg(...) |
ggplot() with geom_line() |
sns.lineplot() |
geom_ribbon() |
ax.fill_between() |
bsicons::bs_icon() |
faicons.icon_svg() |
Translate the Beta-Binomial app from last lecture into Shiny for Python.
Add the packages used by the app and the accompanying examples:
The options are the same as for R, and so is the advice about keeping an app in a single folder with relative paths.
requirements.txt listing the app’s packages, which uv can write.shinylive bundles the app as a static site that runs entirely in the browser using Pyodide. Packages with compiled code need Pyodide-compatible builds; many pure-Python packages also work. numpy, pandas, scipy, and matplotlib are available.| Concept | R | Python |
|---|---|---|
| app object | shinyApp(ui, server) |
app = App(app_ui, server) |
| run | runApp() |
shiny run --reload app.py |
| input widget | sliderInput("x", ...) |
ui.input_slider("x", ...) |
| output placeholder | plotOutput("plot") |
ui.output_plot("plot") |
| read an input | input$x |
input.x() |
| output | output$plot = renderPlot({...}) |
@render.plot on def plot(): |
| reactive expression | d = reactive({...}) |
@reactive.calc on def d(): |
| observer | observe({...}) |
@reactive.effect on def _(): |
| event | bindEvent(input$run) |
@reactive.event(input.run) |
| update an input | updateSliderInput(session, "x", ...) |
ui.update_slider("x", ...) |
| dynamic UI | uiOutput(), renderUI() |
ui.output_ui(), @render.ui |
| splice a list | !!!boxes |
*boxes |
| HTML class | class = "p-2" |
class_="p-2" |
Shiny for Python is a separate implementation of the same design. The UI and server split, the reactive graph, and the bslib components all carry over from R.
A decorator passes the function below it to another function and rebinds the name to the result. Shiny uses decorators wherever R wraps a block of code in a function call, so renderPlot({}), reactive({}), and observe({}) become @render.plot, @reactive.calc, and @reactive.effect.
An output is matched to the UI by the name of its function. Most output renderers require an explicit return; @render.plot can also capture pyplot drawing without one.
Reactive values are read by calling them, as in input.x(). They are passed without parentheses to @reactive.event(), which sits directly above the def.
UI functions live in ui with snake_case names. Children come first as positional arguments and named options follow.
Sta 523 - Fall 2026