How to properly set st.session_state in streamlit

So I have such sample code. As you can see locale setted twice. However I keep getting error:

AttributeError: st.session_state has no attribute “locale”. Did you forget to initialize it? More info: Add statefulness to apps - Streamlit Docs

What is wrong here?

   import streamlit as st
    from dataclasses import dataclass
    
    @dataclass
    class Locale:
        ai_role_prefix: str
    
    
    # --- LOCALE SETTINGS ---
    en = Locale(
        ai_role_prefix="base",
    )
    
    if 'locale' not in st.session_state:
        st.session_state.locale = en
    
    if __name__ == "__main__":
        st.session_state.locale = en
        print(st.session_state.locale.ai_role_prefix)

After fixing the indentation I could run your code without any errors. You must be running some other code.

1 Like

Wow you were right, it works from console this way “streamlit run .\temp.py” but fails to run from pycharm as standart python code

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