Re-import modules when the page is reloaded


i want streamlit to re-import my modules—specifically, some imported variables—when the user refreshes the page.

currently, the only workaround that i found is re-running the script, but i don’t want to do this all the time. also, st.rerun() only seems to re-initialize the st.session_state object. moreover, i’d need to execute this re-initialization only with refreshings—which may or may not include a manual st.rerun().

here is what i tried:

if "reload" not in st.session_state:
    st.session_state.reload = True
    del my_variable
    from my_module import my_variable

weirdly, this doesn’t seem to perform the import operation at all—although the block runs.

i’m not accesing this variable from st.session_state, but i think it would be the same, because i would instantiate it with the previously imported variable that i’m not being able to re-import.


Not sure I completely understand, when a user refreshes the page it should re-execute every line of code on that page. If I had to guess, if your variables are not reloaded you have cached their values.

If you could provide a minimal code example it would be helpful.

thanks! i’ve just updated the main message with a code example

I found a way. It involves importing the whole module and reimporting it within that conditional clause using importlib.reload(my_module). I don’t know if it is possible to import just some variables of that module. But I guess this is a Python issue.

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