Cache results when editing python?

The caching system in Streamlit seems very powerful. There are many times when I am slightly tweaking python logic during development. In a traditional notebook workflow, I can rapidly iterate on a single cell. I am noticing in Streamlit, whenever I tweak 1 thing about the Python file, the entire app re-runs (including inference, etc).

Is there any way to have only part of the python codepaths re-run when editing the code itself? This would make it a lot easier to iterate with quickly.

Hi @kossnick

Is there any way to have only part of the python codepaths re-run when editing the code itself?

Not at the moment.

Stepping back for a sec, with Streamlit’s existing caching system it makes most sense to factoring your code into subfunctions as you go. This is the recommended way to work with Streamlit. In our experience this produces the best, longest-lasting code — and over time this style of exploratory coding becomes second nature.

That said, if you want to do “notebook cell” style coding, you can hackier way to do the above would be to put just blindly put each “cell” in to its own function:

import streamlit as st

@st.cache
def first_cell():
  # do stuff
  return x, y

x, y = first_cell()

@st.cache
def second_cell():
  # do stuff
  return z

z = second_cell()

# Code you're still iterating on:
st.write(x + y + z)

The main downside is that this requires quite a bit of boilerplate for each “cell”. Which is why we have an upcoming feature that will make this style of coding much easier (just 1 line of code per cell!), but that will take 1+ months to land.

1 Like

Thanks for the detailed reply. To clarify, your above code would enable caching on re-running, correct? I had thought that would be only when UI interactions happen. Does it also cache when the Python code itself changes and you are in the mode of “Always rerun”?

1 Like

Yes.

As I understand it the cache is used both when the user interacts and when the code is changed.