Cache function within class with Streamlit

Viewed 568

I have the following class, whose function "expensive_computation"'s result I would like to cache:

class c:
    def download_from_GCS(self, b, c):
        print(b + c)
    
    @st.cache(suppress_st_warning=True)
    def expensive_computation(self, a):
        self.download_from_GCS(b=a, c=a+10)
        print(a)


c().expensive_computation(a=1)

Without the Streamlit cache indication, the code correctly works; however, as soon as it is introduced, the following error is raised:

InternalHashError: module '__main__' has no attribute '__file__'

While caching the body of `expensive_computation()`, Streamlit encountered an
object of type `builtins.function`, which it does not know how to hash.

In the meantime, you can try bypassing this error by registering a custom
hash function via the `hash_funcs` keyword in @st.cache(). For example:

```
@st.cache(hash_funcs={builtins.function: my_hash_func})
def my_func(...):
    ...
```

If you don't know where the object of type `builtins.function` is coming
from, try looking at the hash chain below for an object that you do recognize,
then pass that to `hash_funcs` instead:

```
Object of type builtins.function: <function c.expensive_computation at 0x7fe84b35d0d0>
```

Please see the `hash_funcs` [documentation]
(https://docs.streamlit.io/library/advanced-features/caching#the-hash_funcs-parameter)
for more details.

I've tried substituting @st.cache(hash_funcs={builtins.function:"function c.expensive_computation at 0x7fe84b35d0d0"}) but it doesn't seem to be working.

How can I correctly cache the final output from "expensive_computation" using Streamlit?

1 Answers

Fixed in a later version of Streamlit.

Output:

12
1
Related