There are some hints in the docs, like this
Singleton objects can be used concurrently by every user connected to your app, and you are responsible for ensuring that @st.singleton
objects are thread-safe . (Most objects you’d want to stick inside an @st.singleton
annotation are probably already safe—but you should verify this.)
Or this
Each singleton object is shared across all users connected to the app. Singleton objects must be thread-safe, because they can be accessed from multiple threads concurrently.
Thread safety is only a concern when you mutate shared state, inmutable (or inmutated, if that is a word) state is always safe.
BTW, be aware of thread safety if you do this. The key-value pair you just wrote might have a different value or not be there at all the next moment because another session changed the shared state.
That should be ok, the same user can use several devices. If you want to keep user-specific state, I can think of two ways of doing it:
-
Making the shared state a dictionary where each key is a user id and the value is the state related to that user.
-
Making the function that return the state take an user id as parameter, so that it returns a different object for each user.
Again, whatever you do, you need to add the concept of a user to your application.
st.experimental_memo
doesn’t cache the return value itself but a serializad version of it
Unlike @st.cache
, this returns cached items by value, not by reference. This means that you no longer have to worry about accidentally mutating the items stored in the cache. Behind the scenes, this is done by using Python’s pickle()
function to serialize/deserialize cached values.
Si it can’t work for shared mutable state because each time you call the function you get a fresh copy of the original object and the cache is not aware of any changes you make to your copy.
st.experimental_user
can be a way to identify the user in very specific cases. Take a look at the docs, in particular how it behaves in different contexts to see if it can be of any use to you.