Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Session State convenience function for initialization #10089

@sfc-gh-dmatthews

Description

@sfc-gh-dmatthews

Checklist

  • I have searched the existing issues for similar feature requests.
  • I added a descriptive title and summary to this issue.

Summary

It'd be nice for Session State to have a convenience method for initializing it.

Why?

Many apps have boilerplate code:

if "my_key" not in st.session_state:
    st.session_state.my_key = "default_value"

If there are multiple keys, you might shortcut the logical test to check for one and initialize all others:

if "A" not in st.session_state:
    st.session_state.A = "A"
    st.session_state.B = "B"
    st.session_state.C = "C"

If any of the keys were associated to a widget and the widget wasn't continuously rendered, you could have a situation will all keys initialized on session start, but maybe "B" or "C" got deleted later. Thus, to be really thorough, you'd need:

session_init = {"A":"A", "B":"B", "C":"C"}
for key, value in session_init.items():
    st.session_state[key] = value

It might be nice to have a convenience function to handle the latter:

st.session_state.from_dict({"A":"A", "B":"B", "C":"C"})

A parameter could be used to distinguish between initializing (set if not exists), updating (dictionary merge), or full replacement (delete other keys).

How?

Similar to how st.query_params is a dict-like interface with a few extra functions, st.session_state could get a convenience function or two.

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature:st.session_stateRelated to session state managementtype:enhancementRequests for feature enhancements or new features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions