# How to use st.cache

**URL:** <https://discuss.streamlit.io/t/how-to-use-st-cache/25704>\
**Category:** Using Streamlit\
**Tags:** cache\
**Created:** [May 27, 2022, 6:52am UTC](https://discuss.streamlit.io/t/how-to-use-st-cache/25704 "2022-05-27T06:52:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![qt.qt](https://avatars.discourse-cdn.com/v4/letter/q/ba9def/32.png) [@qt.qt](https://discuss.streamlit.io/u/qt.qt)\
**Post date:** [May 27, 2022, 6:52am UTC](https://discuss.streamlit.io/t/how-to-use-st-cache/25704/1 "2022-05-27T06:52:32Z")

</div>

Hello all from the documentation of streamlit I understand that using the @st.cache will just execute the function once. Because I wouldn’t want to keep connect to database every time the script is reruns. From my code below I have this function that does the initialization of the database and other function would make use of this object to get data from the database. However, when script is started, after running for quite sometime there will be this internal hash error. It says that maximum recursion depth exceed in comparison. Streamlit encountered an object of type builtins.method which it does not know how to hash.

Is this the correct way to cache an object for use in other function?

```auto
from database import db 
import streamlit as st 

@st.cache(hash_funcs={db: lambda _: None}) 
def init_db():
      database = db()
      database.init()
      return database

database = init_db()

def get_data():
        st.text(database.get_data())

```

---

<div class="post-metadata">

**Author:** ![randyzwitch](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/randyzwitch/32/58772_2.png) [@randyzwitch](https://discuss.streamlit.io/u/randyzwitch)\
**Post date:** [May 27, 2022, 2:06pm UTC](https://discuss.streamlit.io/t/how-to-use-st-cache/25704/2 "2022-05-27T14:06:23Z")

</div>

Hi @qt.qt -

What happens when you name your objects something other than `database`? In your code, you have a reference to a module `database`, but then you also run `database = init_db()`. Mentally, I’m not sure exactly what would happen here with the Streamlit processing model, as `database` name binding would (possibly?) go back and forth between being a module, being a database object that’s cached, and back.

Best,  
Randy

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/streamlit/original/3X/c/f/cf4c2ee0d938358f82448c5fe4b9c3c91d7ce19c.svg) [@system](https://discuss.streamlit.io/u/system)\
**Post date:** [May 27, 2023, 2:06pm UTC](https://discuss.streamlit.io/t/how-to-use-st-cache/25704/3 "2023-05-27T14:06:30Z")

</div>

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