How to interact with python?

with this code type in text into the textbox and hit the button. I’d like to add items to β€œa” list and keep them there.
Is there a better way to do this?

import functools
import streamlit as st

st.title('interactivity problems saving to lists')
st.subheader('a is a list')
st.subheader("saving things to a container wasn't any better")

a = list()


def fn(new_thing):
    st.write(new_thing)
    a.append('static item in the function')
    a.append(new_thing)
    with col1:
        st.write(a)


ta = st.text_area('Enter a thing to save, it should output below')
st.button("append to list", on_click=functools.partial(fn, ta))

a.append("static item almost at the end")
st.write("the list is: ", a)
col1, col2, = st.columns(2)

Hi @jlangley, the best option for keeping track of something like that, that should persist and get added to even if the script gets rerun, is to use st.session_state Session State - Streamlit Docs

Here’s an example of what that might look like:

import streamlit as st

st.title("interactivity problems saving to lists")
st.subheader("a is a list")
st.subheader("saving things to a container wasn't any better")

if "mylist" not in st.session_state:
    st.session_state["mylist"] = []


def fn(new_thing):
    st.write(new_thing)
    st.session_state["mylist"].append("static item in the function")
    st.session_state["mylist"].append(new_thing)
    with col1:
        st.write(st.session_state["mylist"])


ta = st.text_area("Enter a thing to save, it should output below")
st.button("append to list", on_click=fn, args=(ta,))

st.session_state["mylist"].append("static item almost at the end")
st.write("the list is: ", st.session_state["mylist"])
(
    col1,
    col2,
) = st.columns(2)

A few things to note:

  1. The functools.partial is a clever solution, but you can also just pass args to your button so that it will pass that argument to the function for you
  2. All of those append calls that aren’t inside of the onclick will get run every time the script runs, so you may end up with more duplicated rows being added to your list than you were hoping for.

Thank you. That worked amazingly.
replying to part two. That was just print statement debugging.

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.