Text input strange behavior when key present

I wanted text input in a loop. st rightly complained about the fields having the same key. When I insert key using random, it stops printing values outside.

The following works fine:

import random
for i in range(1): # single field
    foo = random.choice(string.ascii_uppercase)+str(random.randint(0,1000))
    myc2 = st.text_input('')
    st.write(myc2,myc2[::-1])

The following complains about same key:

import random
for i in range(3): # loop and no key
    foo = random.choice(string.ascii_uppercase)+str(random.randint(0,1000))
    myc2 = st.text_input('')
    st.write(myc2,myc2[::-1])

The following stops printing the string and its reverse:

import random
for i in range(3): # loop and key
    foo = random.choice(string.ascii_uppercase)+str(random.randint(0,1000))
    myc2 = st.text_input('',key=foo)
    st.write(myc2,myc2[::-1])

The issue seems to be with the key since it also fails to print for loop of 1 with key
import random

for i in range(1): # no loop; key yes
    foo = random.choice(string.ascii_uppercase)+str(random.randint(0,1000))
    myc2 = st.text_input('',key=foo)
    st.write(myc2,myc2[::-1])

Baffled ;-(

Do others see the same thing?

Hi @AshishMahabal, welcome to the Streamlit community!

What you are seeing is one of the underlying mechanisms of how Streamlit works. In your first code snippet, you are creating a single st.text_input widget, so Streamlit can determine with certainty which one you are referring to.

In the second snippet, now you define a st.text_input 3 times; this does not overwrite the text_input, but rather orphans the references to the other ones (but the front end is still keeping track). So you get a key error.

If you want to keep writing over the same widget, put an st.empty() outside of your loop:

If your code has to be this way for some reason, you can add a key argument to st.text_input…set that value to your loop value i to make distinct text_input widgets.

Best,
Randy

1 Like

Hi @randyzwitch,

Thank you for your reply. I roughly understand the orphaning part, but still not the flow.

In the code below where I have a loop of 1, so no multiple text inputs, and I assign a random key inside that loop, it still does not print myc2. Where/when does it’s value become stale?

On the other hand, if I use the loop variable as key, then it prints myc2.
What is different in the two?

For my original question I did go ahead and use st.empty() (recursively, no less) and get my problem solved. Thank you again for your reply.