Create session states in a loop?

Hello! I was wondering if it was possible to create session states in a loop. for example: for each item in a list, generate a session state and for each session state show a unique input text field.

Thanks in advance!

Hi Caio and welcome
It is possible to create and track multiple session states but it requires a modification to the [not officially supported!] SessionState gist. I did this to maintain a stack of states, one for each ‘page’ class in a multiple page application. There is a summary and a copy of the code here.

Note that this needs to be updated to reflect the new version of the SessionState gist for Streamlit 0.54 and above. That’s a simple copy/paste job but I’m not on my work machine at present.
I expect to have to refactor/replace this when Streamlit finalizes its session tracking approach.

Thank you for the quick response Kevin!

I have created a single state variable for each relevant variable beforehand and that works! But I have not been able to create session state variables in a loop. Not sure if it is a streamlit limitation or my own limitation trying to code this.

For example, user chooses a number from 1 to 10 from a number input box, if the number 8 is chosen, 8 separate text input boxes will be displayed, each with its own session state variable. My work around was if statements instead, but it makes the code a bit longer and less flexible.

Caio
If I have got this right you have two page runs, at least to start with. The first collects the number of text boxes (8), the second displays the 8 boxes. After that each time you get an input in a box the page reruns displaying all the boxes till you are done.

I don’t think you need a sessionstate per box for this. The function of the SessionState gist is to provide a hook to transfer information from one run to the next. The way I handle this kind of situation is to store the information I want available “next time” as an attribute of the returned SessionState object. That attribute can be a list or a dict etc. That’s a lot easier to construct and parse.

Kevin,

Yes, that is it! I will give it a try soon and let you know if I get anywhere.

Thanks again for the quick responses!