Variables gets reinitialize on hard refresh

@Shawn_Pereira
you told about this

  1. Some widgets (like buttons) cause a streamlit refresh (re-running of code from the top)
  2. In such a scenario, if you have a variable:
    a. initially set to a certain value, and
    b. later change the variable value, and
    c. press the widget that causes a refresh
    your variable will again start with its initial defined value

If you want a variable to persist its value across refreshes, you need to define it as a session state variable by the statement:
if "my_variable_name" not in st.session_state: st.session_state.my_variable_name = "xyz"
This records the variable in the program’s session state and initializes it to the value ‘xyz’
Future changes to that variable in your code must be made by the statement: st.session_state.my_variable_name = "pqr"
Now the variable will have its last assigned value across refreshes (i.e pqr).

But actually the my_variable_name =“xyz” and gets reinitalize again on hardrefeshing the page.
Could you suggest something to cope with this

Hi @Ashutosh

For hard refreshes, you could try something like cookies - a text file. The probable steps would be:

  1. When your programs starts, it checks if this text file (having a certain name) exists in your application path / home directory.
    a. if exists, it opens the file, reads the contents, and sets the variable name to the contents of the text file
    b. if it does not exist: it creates a text file and stores an initial variable value (eg. xyz) in it

  2. Every time you change the variable name (Eg. pqr) further down your program, you rewrite the text file with the new variable value

  3. On next startup / hard refresh, the program will detect that the text file exists and will initialize your session state variable to the last written text file value (as per process described in step 1a above)

Cheers