Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 38 ยท Getting Started

Magic, st.write and Page Configuration

Learn how st.write displays almost anything, how Streamlit magic shows bare variables, how to set the page title, icon and layout, and how to structure an app file.

You now know that Streamlit reruns your script. This lesson covers three things you will use in every app: st.write, the "magic" feature that displays values without any call at all, and st.set_page_config, which controls the browser tab and overall page layout. We finish with a reliable file structure for a growing app.

All Streamlit code in this lesson is real and read-only; the runnable blocks are labelled stand-ins that show how the ideas work.

st.write: the Swiss army knife

st.write() takes one or more arguments and chooses how to display each by its type:

Python
import pandas as pd
import streamlit as st

st.write("Plain text and **Markdown** work.")
st.write("A number:", 42, "and a list:", [1, 2, 3])
st.write({"name": "Ada", "age": 36})          # a dictionary: shown as JSON
st.write(pd.DataFrame({"x": [1, 2], "y": [3, 4]}))   # a table

On the page you would see a paragraph with bold text, a line with the number and list, an expandable JSON-style view of the dictionary, and a small interactive table. A string is rendered as Markdown, so "# Heading" becomes a heading and "code" becomes inline code. A DataFrame is displayed like st.dataframe, a Matplotlib figure like st.pyplot, an exception as a red error with a traceback, and so on. Unknown objects fall back to their text form.

st.write is convenient when you are exploring. When you want control (the exact table options, a chart type, a heading level), use the specific function: st.markdown, st.dataframe, st.pyplot. The next chapter covers them.

Magic: bare values are displayed

Streamlit has a feature called magic. When your script contains an expression on its own line, with nothing assigned and no function call you wrote yourself, Streamlit automatically wraps it in st.write. So this works:

Python
import pandas as pd

"# Sales report"              # shown as a heading

df = pd.DataFrame({"city": ["Oslo", "Lima"], "units": [120, 90]})
df                            # shown as a table

df["units"].sum()             # shown as the number 210

You did not even import streamlit there, yet the page shows a large heading, a table and the number 210. Magic is great for quick experiments and notebooks-style scripts. Know its limits:

  • Only bare expressions on their own line are displayed. An assignment (x = 5) shows nothing.
  • Magic is meant for the script's top level and its if, for and with blocks. Inside your own functions, call st.write explicitly so the behavior is obvious.
  • A docstring at the very top of a module is rendered as Markdown too (it is just a bare string).
  • In shared code and bigger apps, explicit st.write is clearer to the next reader.

How magic works (stand-in)

Streamlit does this by parsing your script into a syntax tree (ast) and rewriting each bare expression statement into a call to st.write. The block below does the same trick with Python's real ast module and a stand-in write. It is not Streamlit's code, but the technique is the same.

Python Stand-in: a tiny version of magic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The heading string, the list and the sum are shown; the two assignments are not. That is the complete rule.

st.write as a type dispatcher (stand-in)

A good way to understand st.write is to imagine a function that looks at the argument's type and picks a renderer. The runnable stand-in below does exactly that with plain pandas; the real function has many more cases and produces rich elements, not text.

Python Stand-in: choose a renderer by type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

st.set_page_config: the page itself

st.set_page_config sets properties of the whole page: the browser tab title, the favicon, the width of the content and the initial state of the sidebar. It must be the first Streamlit command in the script, and it can be called only once per page. Anything that draws to the page before it raises an error.

Python
import streamlit as st

st.set_page_config(
    page_title="Sales Dashboard",
    page_icon="๐Ÿ“ˆ",
    layout="wide",
    initial_sidebar_state="expanded",
)

st.title("Sales Dashboard")
Argument Values Effect
page_title string Text in the browser tab and bookmarks
page_icon emoji, image path, or Material icon like ":material/home:" Favicon in the tab
layout "centered" (default) or "wide" Narrow reading column versus full browser width
initial_sidebar_state "auto", "expanded", "collapsed" Whether the sidebar starts open
menu_items dict with "Get help", "Report a bug", "About" Customizes the top-right menu

"centered" keeps lines short and readable, which is right for text and forms. Use "wide" for dashboards with several columns of charts. In a multipage app (see Multipage Apps), call st.set_page_config in the entry file; it applies to every page unless a page calls it again.

Debug helpers

  • st.help(obj) shows the documentation of any Python object, handy while learning.
  • st.echo() is a context manager that runs a block and displays its source code, great for tutorials:
Python
import streamlit as st

with st.echo():
    total = sum(range(5))
    st.write("Total:", total)

The page shows a code box with both lines, then the output "Total: 10".

A reliable app structure

A readable app follows the same order almost every time. Keeping to it prevents errors such as set_page_config being called too late.

Python
# 1. imports
import pandas as pd
import streamlit as st

# 2. page configuration: FIRST Streamlit call
st.set_page_config(page_title="Sales", layout="wide")

# 3. cached helpers (functions with @st.cache_data)
@st.cache_data
def load_data():
    return pd.read_csv("sales.csv")

# 4. sidebar and input widgets
region = st.sidebar.selectbox("Region", ["All", "North", "South"])

# 5. data logic (plain pandas)
df = load_data()
if region != "All":
    df = df[df["region"] == region]

# 6. output: title, metrics, charts, tables
st.title("Sales")
st.dataframe(df)

Put logic that does not draw anything (loading, cleaning, calculating) in ordinary functions. They are easier to test and can run in plain Python without a server; see the pandas lessons on cleaning data and group by.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must st.set_page_config be called?

    It configures the whole page, so it must run before any other Streamlit element is drawn, and only once per page.
  2. 2. In magic mode, which line displays something on the page?

    A bare expression on its own line is wrapped in st.write. Assignments, imports and definitions are statements and show nothing.
  3. 3. How does st.write treat the string '# Title'?

    Strings are rendered as Markdown.
  4. 4. Which layout value gives the content the full browser width?

    layout can be 'centered' (default) or 'wide'.

Summary

  • st.write renders strings as Markdown and shows DataFrames, dicts, figures and more by type.
  • Magic displays bare expressions automatically; assignments and imports show nothing.
  • st.set_page_config sets title, icon, layout and sidebar state and must be the first Streamlit call.
  • Structure an app as imports, config, cached helpers, inputs, logic, output.

Next: Text Elements