当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Streamlit st.experimental_singleton用法及代码示例


存储单例对象的函数装饰器。

每个单例对象都在连接到应用程序的所有用户之间共享。单例对象must 是线程安全的,因为它们可以同时从多个线程访问。

(如果线程安全是一个问题,请考虑使用st.session_state来存储 per-session 单例对象。)

您可以使用 f.clear() 清除 memory 函数的缓存。

函数签名

st.experimental_singleton(func=None, *, show_spinner=True, suppress_st_warning=False)
参数说明

func (callable)

创建单例的函数。 Streamlit 散列函数的源代码。

show_spinner (boolean)

启用微调器。默认为 True 以在存在 "cache miss" 并且正在创建单例时显示微调器。

suppress_st_warning (boolean)

禁止从单例函数中调用 Streamlit 函数的警告。

示例

@st.experimental_singleton
 def get_database_session(url):
     # Create a database session object that points to the URL.
     return session

s1 = get_database_session(SESSION_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

s2 = get_database_session(SESSION_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value. This means that now the connection object in s1 is the same as in s2.

s3 = get_database_session(SESSION_URL_2)
# This is a different URL, so the function executes.

默认情况下,单例函数的所有参数都必须是可散列的。任何名称以开头的参数_不会被散列。对于不可散列的参数,您可以将其用作"escape hatch":

@st.experimental_singleton
 def get_database_session(_sessionmaker, url):
     # Create a database connection object that points to the URL.
     return connection

s1 = get_database_session(create_sessionmaker(), DATA_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

s2 = get_database_session(create_sessionmaker(), DATA_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value - even though the _sessionmaker parameter was different
# in both calls.

可以通过程序清除单例函数的缓存:

@st.experimental_singleton
 def get_database_session(_sessionmaker, url):
     # Create a database connection object that points to the URL.
     return connection

get_database_session.clear()
# Clear all cached entries for this function.

相关用法


注:本文由纯净天空筛选整理自streamlit.io大神的英文原创作品 st.experimental_singleton。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。