Alternative implementation of session state

Slightly better example using a dataclass and not passing kwargs:

import streamlit as st

from session_state import get_state

@dataclass
class MyState:
    a: int
    b: str

def setup() -> MyState:
    print('Running setup')
    return MyState(a=3, b='bbb')

state = get_state(setup)

st.title('Test state')
if st.button('Increment'):
    state.a = state.a + 1
    print(f'Incremented to {state.a}')
st.text(state.a)

Iā€™ve been using this setup for the past few days with great success. It really makes buttons more useful when state can be stored.

4 Likes

Hi @biellls

I really like it.

Is it possible to do an additional simplification of the api?

I imagine you could actual ā€œhideā€ the setup function in you session_state.py file and change the public api from state = get_state(setup) to state=get_state(a=3, b='bbb').

Marc

Hi @Marc, thanks for the feedback. What youā€™re proposing is basically what was implemented in the original gist if I understood correctly. Let me try to explain why I think my way is an improvement over that for two reasons:

  1. Arguments get evaluated every time thereā€™s a re-run, so if you want to open a database connection and you do state=get_state(db=psycopg2.connect("dbname=test user=postgres password=secret")) youā€™ll be opening it lots of times.
    The reason I added a setup function is that this way we can guarantee that the code inside it runs exactly once, which is what a setup should do.
    Ideally weā€™d have that in a closure/multi-line lambda but python doesnā€™t allow those (and regular lambdas are untyped) so I had to make it a function.

  2. You lose typing information. The original get_state is an object that gets added instance variables dynamically, whereas in mine I created a class/dataclass. Since that class/dataclass is the return of my setup function, get_state can infer that itā€™s returning that class/dataclass and then type checking/code complete works in the editor.

Makes sense. Thanks.

Very cool. Weā€™ve been thinking about this as well and will post some possible designs. :+1:

A more generic solution for Classes which the only downside is that all parameters must be initialized with default values.

def MyClass:
    __init__(self, a=None, b=None):
        self.a = a
        self.b = b


def get_class(class_, **kargs):
    return class_(**kargs)

Example:
my_class = get_state(get_class, class_=MyClass, a=a, b=b)

@biellls thanks for so useful functions :smiley:

1 Like

Hello,

Iā€™m getting this error:

AttributeError: ā€˜ReportSessionā€™ object has no attribute ā€˜_main_dgā€™

Traceback:

  File "e:\anaconda3\envs\myenv\lib\site-packages\streamlit\ScriptRunner.py", line 314, in _run_script
    exec(code, module.__dict__)
  File "CompareModels_img.py", line 139, in <module>
    session_state = SessionState.get(question=1)
  File "streamlit_utils.py", line 61, in get
    if session_info.session._main_dg == ctx.main_dg:

any idea how to fix it?

This is the solution I came up with:

class Session:
    pass

@st.cache(allow_output_mutation=True)
def fetch_session():
    session = Session()
    session.question = 1
    return session

session_state = fetch_session()

it works so far

Also getting AttributeError: 'ReportSession' object has no attribute '_main_dg' error.

downgraded streamlit version to 0.50.2 and it works now.

Hey there! There is a gist for the session state. From streamlit changelog:
If youā€™re using the SessionState hack Gist, you should re-download it! Depending on which hack youā€™re using, here are some links to save you some time:

Source: https://docs.streamlit.io/changelog.html#version-0-56-0

2 Likes

should I just include this in the session state file or ?

I am having difficulty with a text_area and I am not sure if it is a bug or I just am not putting it together correctly.

I put in a bug report, but maybe I should have started here.

I want to be able to update a text area and maintain the state, but when the text area only seems to update every other change.

import streamlit as st
import SessionState

session_state = SessionState.get(template_string="None")
st.write(session_state.template_string)
template_string = st.text_area("Test", session_state.template_string, height=200)
session_state.template_string = template_string

Can someone use the above example and update the text area a few times and tell me if that is the expected behavior? It seems to only update every other text_area change and revert back to the old state when it doesnā€™t update.

Hey @jetilton,

Iā€™ve implemented yet another session state which tackles your exact problem : Multi-page app with session state

I solved the issue by doing a rerun each time a value is set in the session state. Feel free to use it as is, or adapt OPā€™s version. Mine doesnā€™t feature python typing.

Tell me how it goes!

1 Like

Thanks @okld, I am going to try this first thing in the morning! Your demo looks awesome, it makes me more excited to use Streamlit now that I see the possibilities.

@okld I couldnā€™t wait and fired up my app again and just dropped in your implementation and it seems like everything just worked. I havenā€™t done any extensive testing, but this looks like it did the trick. THanks again.

2 Likes

Have been jiggling around the session for the past few days now.

a button selection will change the state and idea here is to get multiple inputs from UI and session should be retained until all fields are entered

import streamlit as st
import SessionState
session_state = SessionState.SessionState(id='abc', country='xyz', currency= 'Rupees')

def main () :
    rerun = st.button('Rerun')
    if rerun :
        st.write('Select from the following to add/edit  :')
        name_dict  = {'id': '' , 'country': '', 'currency' : ''}

        state = SessionState.get(id='abc', country='xyz', currency= 'Rupees')

        for k, v in name_dict.items():
            name_dict[k] = st.text_input(k, v)
            state.k =   name_dict[k]
            st.write(name_dict[k])            

main()   

This does not seem to work.
After 1st input, app gets refreshed and data is lost

1 Like

Hello @Ramyashree,

Each time you interact with a widget, the whole script reruns. In your example:

  • I click on Rerun --> the script reruns and the button returns True. I enter the conditional block.

  • st.text_inputs are created. I input some text in one of them --> As I validate my first input, the whole script reruns, but the Rerun button returns False this time as it doesnā€™t maintain any state. Widgets disappear and values are lost.

The solution would be to preserve the buttonā€™s state to enter the conditional block as long as inputs are not all filled.

If youā€™re open to other suggestions, Iā€™d say you should display text_inputs from the beginning, and when you press the button, it does the processing. This way, you donā€™t need session states anymore, and even for the end-user, it may be better to present things this way.

2 Likes

@okld

Thanks for your response.
I did a workaround for this as you suggested and it worked.

used checkbox to collect data from UI, as checkboxes will retain the data through runs
used button to process collected data. it works like a pro.

2 Likes

You can use it as is. This might make it more obvious:

class Session:
    pass

@st.cache(allow_output_mutation=True)
def fetch_session():
    session = Session()
    session.counter = 1
    return session

def main():
    session_state = fetch_session()
    session_state.counter += 1
2 Likes