Created
October 19, 2019 16:28
-
-
Save treuille/75696b0e4c1c8b0aaf45d37386f6af5e to your computer and use it in GitHub Desktop.
Workaround: Partial Caching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import streamlit as st | |
import functools | |
def partial_cache(func=None, **cache_kwargs): | |
"""Like st.cache, but if the function returns None, then nothing is cached. | |
Parameters | |
---------- | |
func : Callable | |
If not None, the function to be cached. | |
**cache_kwargs | |
You can pass any other arguments which you might to @st.cache | |
""" | |
# Support passing the params via function decorator | |
if func is None: | |
return lambda f: partial_cache( | |
func=f, | |
**cache_kwargs | |
) | |
# Indicate that we shouldn't cache the result | |
class DontCache(Exception): | |
pass | |
# Like func() but throws an exception instead of returning None | |
@st.cache(**cache_kwargs) | |
def func_or_dont_cache(*args, **kwargs): | |
return_value = func(*args, **kwargs) | |
if return_value == None: | |
raise DontCache | |
return return_value | |
# Caches the return value only if not None | |
@functools.wraps(func) | |
def wrapped_func(*args, **kwargs): | |
try: | |
return func_or_dont_cache(*args, **kwargs) | |
except DontCache: | |
return None | |
return wrapped_func | |
def partial_cache_example(): | |
"""Demonstrates how to use the @partial_cache decorator.""" | |
@partial_cache(suppress_st_warning=True) | |
def even_or_odd(i): | |
if i % 2 == 0: | |
st.write(i, 'is even. (Caching.)') | |
return True | |
else: | |
st.write(i, 'is odd. (Not caching.)') | |
return None | |
st.write('### These will all display.') | |
even_or_odd(1) | |
even_or_odd(2) | |
even_or_odd(3) | |
even_or_odd(4) | |
st.write('### Only the evens will display. The odds are cached') | |
even_or_odd(1) | |
even_or_odd(2) | |
even_or_odd(3) | |
even_or_odd(4) | |
if __name__ == '__main__': | |
partial_cache_example() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment