basic sequential execution flow

Hi,

My app runs locally. Streamlit version 1.53. Python version 3.11.

Consider the following code

import streamlit as st

def double(input_value):
   return input_value*2

def add(value_1, value_2):
   return value_1 + value_2

def multiply(value_1, value_2):
  return value1 * value2


input_1 = st.number_input("Input 1", min_value=10, max_value=100, value=20, step=10, key="input_1")

output_1 = double(input_1)

input_2 = st.number_input("Input 2", min_value=10, max_value=100, value=20, step=10, key="input_2")

output_2 = add(output_1, input_2)

input_3 = st.number_input("Input 3", min_value=10, max_value=100, value=20, step=10, key="input_3")

output_3 = multiply(output_2, input_3)

st.write(output_3)

This app will run fully the first time. But then, what would be the best way to change my code so that:

  • if input_1 is changed, run fully the app
  • if input_2 is changed, run add and multiply functions only, skipping the double function
  • if input_3 is changed, run multiply function only, skipping the double and add functions

I read the documentation about caching or fragment.
For this simple example, i might manage to find a workaround with fragment but imagine that there are more than 10 inputs and functions sequencially, what would be the best approach to take to avoid rerunning the full app ?

Thank you,

BR

Gui

Hey Gui, thanks for your thoughtful question! You’re right—by default, Streamlit reruns the entire script from top to bottom on any widget interaction. For your use case, the best approach is to use the new fragment feature (introduced in Streamlit 1.37.0), which allows you to rerun only specific parts of your app when certain widgets are interacted with. This is much more scalable than workarounds with caching or session state, especially as your app grows in complexity.

With fragments, you can wrap each logical section (e.g., each function and its associated input) in an @st.fragment-decorated function. When a user interacts with a widget inside a fragment, only that fragment reruns, not the whole script. This lets you control which computations are triggered by which inputs. For more details and examples, see the Streamlit fragments documentation.

Sources: