當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Streamlit st.experimental_memo用法及代碼示例

用於 memory 函數執行的函數裝飾器。

Memoized 數據以"pickled" 形式存儲,這意味著 memoized 函數的返回值必須是 picklable 的。

memory 函數的每個調用者都會獲得自己的緩存數據副本。

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

函數簽名

st.experimental_memo(func=None, *, persist=None, show_spinner=True, suppress_st_warning=False, max_entries=None, ttl=None)
參數說明

func (callable)

要 memory 的函數。 Streamlit 散列函數的源代碼。

persist (str or None)

將緩存數據持久保存到的可選位置。目前,唯一有效的值是"disk",它將持久化到本地磁盤。

show_spinner (boolean)

啟用微調器。默認為 True 以在緩存未命中時顯示微調器。

suppress_st_warning (boolean)

禁止從緩存函數中調用 Streamlit 函數的警告。

max_entries (int or None)

保留在緩存中的最大條目數,或 None 用於無界緩存。 (將新條目添加到完整緩存時,將刪除最舊的緩存條目。)默認值為無。

ttl (float or None)

將條目保留在緩存中的最大秒數,如果緩存條目不應過期,則為 None。默認值為無。

示例

@st.experimental_memo
 def fetch_and_clean_data(url):
     # Fetch data from URL here, and then clean it up.
     return data

d1 = fetch_and_clean_data(DATA_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

d2 = fetch_and_clean_data(DATA_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value. This means that now the data in d1 is the same as in d2.

d3 = fetch_and_clean_data(DATA_URL_2)
# This is a different URL, so the function executes.

設置堅持參數,使用該命令如下:

@st.experimental_memo(persist="disk")
 def fetch_and_clean_data(url):
     # Fetch data from URL here, and then clean it up.
     return data

默認情況下,memoized 函數的所有參數都必須是可散列的。任何名稱以開頭的參數_不會被散列。對於不可散列的參數,您可以將其用作"escape hatch":

@st.experimental_memo
 def fetch_and_clean_data(_db_connection, num_rows):
     # Fetch data from _db_connection here, and then clean it up.
     return data

connection = make_database_connection()
d1 = fetch_and_clean_data(connection, num_rows=10)
# Actually executes the function, since this is the first time it was
# encountered.

another_connection = make_database_connection()
d2 = fetch_and_clean_data(another_connection, num_rows=10)
# Does not execute the function. Instead, returns its previously computed
# value - even though the _database_connection parameter was different
# in both calls.

memory 函數的緩存可以通過程序清除:

@st.experimental_memo
 def fetch_and_clean_data(_db_connection, num_rows):
     # Fetch data from _db_connection here, and then clean it up.
     return data

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

相關用法


注:本文由純淨天空篩選整理自streamlit.io大神的英文原創作品 st.experimental_memo。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。