St.experimental_fragment issue with dynamically created containers

Hi,

python==3.10.2
streamlit==1.34.0
I need to display dynamically created rows within the fragment. Each row is wrapped in the container. Each fragment rerun doesn’t clear out the containers created with the prior run.

full sample code below
When I select 5 rows, I get 5 containers, but after I slide down to 1 row, these containers do not get cleared.

import streamlit as st

cnt_top = st.container(height=100, border=True)
cnt_top.write("TOP")

cnt_slider = st.container()

cnt_rows = st.container(height=300, border=True)


@st.experimental_fragment
def draw_rows(container_slider_empty, container_rows_empty):
    row_count = container_slider_empty.slider("Number of rows", 1, 5, 1)
    row_container = container_rows_empty.container()
    with row_container:
        for idx in range(row_count):
            with st.container(height=50, border=True):
                st.write(idx)


draw_rows(cnt_slider.empty(), cnt_rows.empty())

It works fine with i.e. dividers, when I use st.divider() instead of st.container() in the loop, I get the expected number of dividers.

st.empty has some odd behavior at times that requires adding a slow-down to correctly clear away and update. Here’s a workaround for the issue:

Try adding this to your fragment:

    container_rows_empty.empty()
    time.sleep(.01)

…as follows:

import streamlit as st
import time

cnt_top = st.container(height=100, border=True)
cnt_top.write("TOP")

cnt_slider = st.container()

cnt_rows = st.container(height=300, border=True)


@st.experimental_fragment
def draw_rows(container_slider_empty, container_rows_empty):
    row_count = container_slider_empty.slider("Number of rows", 1, 5, 1)
    container_rows_empty.empty()
    time.sleep(.01)
    row_container = container_rows_empty.container()
    with row_container:
        for idx in range(row_count):
            with st.container(height=50, border=True):
                st.write(idx)


draw_rows(cnt_slider.empty(), cnt_rows.empty())

You can play with the time to try and get it as small as possible. If you hit inconsistent behavior, that’s a cue to increase the time.

Thanks a lot, the workaround appears to work fine.

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