Running function just once and store

I have this function that read configuration files and would like to just run once. but it seems like I canā€™t access it again even if I store it as a session state.

Import streamlit as st
Import configparser 
config_file = ā€œconfig.iniā€

@st.cache(hash_funcs = {configparser.ConfigParser: lambda _: None})
def read_config_files():
      config = configparser.ConfigParser()
      config.read(config_file)
       if ā€˜configā€™ not in st.session_state:
            st.session_state.config = config

def load_page():
      st.title(st.session_state.config[st][page_title])

if __name__   == ā€œ__main__ā€:
       
       load_page()

There is this error stating st.session_state has no key config. Did you forget to initialize? How do I go about running a particular function just once and of storing objects?

Hi @qt.qt -

You donā€™t need to use session_state here. You can just create a variable that references the data, something like:

import streamlit as st
import configparser

config_file = "config.ini"

@st.experimental_singleton
def read_config_files(config_file):
      config = configparser.ConfigParser()
      config.read(config_file)
      return config

data = read_config_files(config_file)

Best,
Randy

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