st.stop() in Streamlit
The st.stop() method is a Streamlit control flow command that immediately stops the execution of your Streamlit script at that line.
๐ Any code written after st.stop() will not run.
Syntax
st.stop()
No arguments are required.
When to Use st.stop()
You typically use st.stop() in situations like:
- Input validation: Stop execution when user input is missing or invalid.
- Early exit: Show only part of the page under certain conditions.
- Authentication / Access control: Stop the app before showing private content.
Example: Stop when required input is missing.
Python
# Importing the Streamlit library
import streamlit as st
st.title("Example: Using st.stop()")
# Ask for user input
name = st.text_input("Enter your name:")
# If no input, show a message and stop further execution
if not name:
st.warning("Please enter your name to continue!")
st.stop()
# This part runs only if the user entered a name
st.success(f"Welcome, {name}! ๐") Explanation
- When the user hasnโt entered a name:
- Streamlit shows the warning.
- st.stop() halts execution โ so the success message doesnโt appear.
- Once the user types their name:
- The condition becomes false, and the script continues.
Example: Use in multi-step workflows.
Python
import streamlit as st
import pandas as pd
st.header("Step 1: Upload a file")
uploaded_file = st.file_uploader("Upload your CSV file")
if uploaded_file is None:
st.info("Please upload a file to continue.")
st.stop()
st.header("Step 2: Display Data")
df = pd.read_csv(uploaded_file)
st.dataframe(df) - โ The file upload must happen first.
- ๐ซ Without a file, no error occurs โ st.stop() cleanly ends execution.