First of all, I think the following phenomenon originally comes from the streamlit’s underlying web framework tornado
but I’d like to know whether it is possible to avoid it on streamlit side.
Problem
If an imported module is stateful, users may see the common information associated to the state across different users’ sessions because streamlit probably do not rerun other modules than the main file when a session is refreshed or newly created.
I believe this is not good for security reason because users see some inputs by other users if such inputs is associated to the modules.
Simple example
x = dict()
import streamlit as st
from sub import x
if "a" not in x:
x["a"] = 0
else:
x["a"] += 1
st.write(x["a"])
and run streamlit run main.py
as usual.
Whenever new session is created, the shown number is increased in this case.
Indeed, the module sub.py
has a mutable variable x and a new or refreshed session refer to the variable without cleaning the module state.
Discussion / Question
Of course, we can avoid it if we confirm one of the rules below:
- only use the main file
- be sure to keep stateless for imported modules and put all states in the session state
However, the first one is unrealistic so that the application becomes more complex to maintain.
The second one is hard to ensure when we have many packages/modules because the class mutable variables frequently used.
(I’m aware of that it is better to avoid class mutable variables as possible ideally.)
Now I’d like to know the following function can be prepared or possible
- Specify the other rerunning imported modules ( sub.py in the above example )
or is there any better solutions ?
Checking or warning the statefulness of modules is other possible one but I think it is not easy…
Honestly speaking, I’m not sure how this becomes problematic in real use cases although I encountered this ( where I define state manager which is a wrapper of session state at other module. ).
And this seems to come from the underlying framework tornado
and may out of scope for streamlit.
Thank you for your attention and I hope better solutions, understandings or having discussions.